这是我的代码:
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"}}
};
我希望在textBox中的这个字典输出中的随机列表中有一个随机项。谢谢,任何帮助表示赞赏!此外,我正在开发Windows Phone 7,如果它有任何不同。
答案 0 :(得分:2)
var rand = new Random();
var randList = dict.Values[rand.Next(dict.Count - 1)];
var randomWord = randList[rand.Next(randList.Count - 1)];
答案 1 :(得分:0)
从这里开始:Random entry from dictionary
有一种更有效的方法可以将字典随机化一次并使其可供选择:
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)];