0

这是我的代码:

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"}}


                       };

我想在文本框中的这个字典输出中的随机列表中有一个随机项目。谢谢,任何帮助表示赞赏!另外,我正在为 Windows Phone 7 开发,如果它有任何不同的话。

4

2 回答 2

2
var rand = new Random();

var randList = dict.Values[rand.Next(dict.Count - 1)];
var randomWord = randList[rand.Next(randList.Count - 1)];
于 2012-04-21T06:51:00.513 回答
0

从这里:字典中的随机条目

有一种更有效的方法可以将字典随机化一次并使其可供选择:

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)];
    }
}

接着:

var rand = new Random();
var randomDict = RandomValues(dict);
var randList = randomDict.First();
var randVal = randList[rand.Next(randList.Count - 1)];
于 2012-04-21T06:58:01.330 回答