从字典中随机项 [英] Random entry from dictionary
问题描述
什么是从一个字典在C#中随机进入的最佳方式?
What is the best way to get a random entry from a Dictionary in c#?
我需要从fictionary得到了一些随机的对象,以显示在页面上,但是我不能用:
I need to get a number of random objects from the fictionary to display on a page, however I cannot use:
Random rand = new Random();
Dictionary< string, object> dict = GetDictionary();
return dict[rand.Next()];
作为字典无法通过索引访问。
as dictionaries cannot be accessed by index.
有什么建议?
推荐答案
的更新使用泛型,甚至更快,以及为什么这个选项比较快的解释。的
这答案是类似于其他反应,但因为你说你需要一些随机元素的这将是更好的性能:
This answer is similar to the other responses, but since you said you need "a number of random elements" this will be more performant:
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;
while(true)
{
yield return values[rand.Next(size)];
}
}
您可以使用此方法像这样:
You can use this method like so:
Dictionary<string, object> dict = GetDictionary();
foreach (object value in RandomValues(dict).Take(10))
{
Console.WriteLine(value);
}
这比对方的反应性能改进(包括yshuditelu的反应)。
This has performance improvements over the other responses (including yshuditelu's response).
- 这并不一定要取一个新的随机值每一次创建所有字典的元素的一个新的集合。这是一个非常大的问题,如果你的字典有很多它的元素。
- 它不具有执行基于字典的关键,每次你取一个随机值查找。不是什么大不了的事#1,但它仍超过两倍这样的。
我的测试表明,在字典中1000个对象,这种方法比另一个建议的方法快约70倍。
My tests show that with 1000 objects in the dictionary, this method goes about 70 times faster than the other suggested methods.
这篇关于从字典中随机项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!