0

here's my code:

var dict = new Dictionary<string, List<string>>
                       {
                            {"AR", new List<string> {"M4A1", "M16A4", "SCAR-L", "CM901", "TYPE 95", "G36C","ACR 6", "MK14", "AK-47", "FAD"} },
                            {"SM", new List<string> {"MP5","UMP45","PP90M1","P90","PM-9","MP7"}},
                            {"LM", new List<string>{"L86 LSW","MG36", "PKP PECHENEG","MK46","M60E4"}},
                            {"SR", new List<string>{"BARRET .50 CAL","L118A","DRAGUNOV","AS50","RSASS","MSR"}},
                            {"SG", new List<string>{"USA512","KS612","SPAS-12","AA-12","STRIKER","MODEL 1887"}},
                            {"RS", new List<string>{"RIOT SHIELD"}}


                       };

I want to have a random item out of a random list in this dictionary output in a textBox. Thanks, any help is appreciated! Also, i'm developing for Windows Phone 7 if it makes it any different.

Lavi
  • 194
  • 3
  • 7
  • 16
  • possible duplicate of [Random entry from dictionary](http://stackoverflow.com/questions/1028136/random-entry-from-dictionary) – Ian Mercer Apr 21 '12 at 07:18

2 Answers2

2
var rand = new Random();

var randList = dict.Values[rand.Next(dict.Count - 1)];
var randomWord = randList[rand.Next(randList.Count - 1)];
SimpleVar
  • 14,044
  • 4
  • 38
  • 60
  • 2
    +1. Note: if not familiar with Random class please read `Random` FAQ at - http://stackoverflow.com/questions/767999/random-number-generator-not-working-the-way-i-had-planned-c to avoid "the same random value all the time" problems. – Alexei Levenkov Apr 21 '12 at 06:53
  • I.e. for testing you sometimes rally want the same "random" sequence/number. But yes, it would be nice to have default behavior less surprising. – Alexei Levenkov Apr 21 '12 at 06:59
  • I would say, let the static be random, and instance be as is. – SimpleVar Apr 21 '12 at 07:03
0

From here: Random entry from dictionary

There is a far more efficient method to randomise the dictionary once and make it available for selection:

public IEnumerable<TValue> RandomValues<TKey, TValue>(IDictionary<TKey, TValue> dict)
{
    Random rand = new Random();
    List<TValue> values = Enumerable.ToList(dict.Values);
    int size = dict.Count - 1;
    while(true)
    {
        yield return values[rand.Next(size)];
    }
}

And then:

var rand = new Random();
var randomDict = RandomValues(dict);
var randList = randomDict.First();
var randVal = randList[rand.Next(randList.Count - 1)];
Community
  • 1
  • 1
yamen
  • 15,390
  • 3
  • 42
  • 52