Quantcast
Channel: Answers by "dubbreak"
Viewing all articles
Browse latest Browse all 68

Answer by dubbreak

$
0
0
Ok, so problem is you can't do exactly what flaviusxvii suggested because you can't index into a keycollection. Of course with linq extension methods you can. Here are two ways: using System.Linq; using System.Collections.Generic; //create dictionary and add stuff to it Dictionary foobarDict = new Dictionary() { {"keyone", new bar()}, {"keytwo", new bar()} }; //solution 1: var randomKey = foobarDict.Keys.ElementAt((int)Random.Range(0,foobarDict.Keys.Count -1)); var randomValueFromDictionary = foobarDict[randomKey]; //solution 2: var randomKey = foobarDict.Keys.ToArray()[(int)Random.Range(0,foobarDict.Keys.Count -1)]; var randomValueFromDictionary = foobarDict[randomKey]; If you use the ToArray it would probably be best to cache the array rather than calling that repeatedly (especially if your dictionary stays static). I'm not sure of the overhead, but it really couldn't hurt. For all I know ElementAt is converting the collection datatype to an array as well before indexing into it. I can't be bothered to look that up. If performance is a concern look it up. Of course it'd be best to abstract this into a method as well.

Viewing all articles
Browse latest Browse all 68

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>