在 C# 中从字典中获取随机条目的最佳方法是什么?
我需要从字典中获取一些随机对象以显示在页面上,但是我不能使用以下内容,因为字典无法通过索引访问:
Random rand = new Random();
Dictionary< string, object> dict = GetDictionary();
return dict[rand.Next()];
有什么建议吗?
最佳答案
如果您使用的是 .net 3.5,Enumerable 有一个扩展方法 ElementAt这将允许你做:
return dict.ElementAt(rand.Next(0, dict.Count)).Value;
关于c# - 从字典中随机输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1028136/