从字典中选择随机列表,从列表中选择随机项目,并将其显示在文本块中
本文关键字:列表 随机 选择 文本 显示 项目 字典 | 更新日期: 2023-09-27 18:31:54
这是我的代码:
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开发,如果它有任何不同的话。
var rand = new Random();
var randList = dict.Values[rand.Next(dict.Count - 1)];
var randomWord = randList[rand.Next(randList.Count - 1)];
从这里开始:从字典中随机输入
有一种更有效的方法可以将字典随机化一次并使其可供选择:
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)];