从集合中随机返回项目 [英] Returning items randomly from a collection
问题描述
我有一个方法从数据库中返回一个通用列表集合(List)。此集合已获得订单详细信息,即订单ID,订单名称,产品详细信息等。
另外,该方法返回的集合仅包含按订单排序的前5个订单日期降序。
我的要求是每次客户调用这个方法时,我需要返回有5个随机订单的集合。
如何使用C#实现这一点?
我写了一个TakeRandom扩展方法,使用 Fisher-Yates shuffle 来做到这一点。这是非常有效的,因为它只是麻烦随机化您实际想要返回的项目数量,并保证不偏不倚。
public static IEnumerable< T> TakeRandom< T>(这个IEnumerable< T>源,int计数)
{
var array = source.ToArray();
return ShuffleInternal(array,Math.Min(count,array.Length))。
}
私有静态IEnumerable< T> (var n = 0; n {
var k = ThreadSafeRandom。 Next(n,array.Length);
var temp = array [n];
array [n] = array [k];
array [k] = temp;
}
返回数组;
ThreadSafeRandom的实现可以是在PFX团队博客中找到。
I've a method which returns a generic list collection(List) from the database. This collection has got order details i.e., Order Id, order name, product details etc.
Also, method the method returns a collection having only the top 5 orders sorted by order date descending.
My requirement is that each time the client calls this method, I need to return collection which has got 5 random orders.
How do I achieve this using C#?
I wrote a TakeRandom extension method a while back which does this using a Fisher-Yates shuffle. It's pretty efficient as it only bothers to randomise the number of items that you actually want to return, and is guaranteed to be unbiased.
public static IEnumerable<T> TakeRandom<T>(this IEnumerable<T> source, int count)
{
var array = source.ToArray();
return ShuffleInternal(array, Math.Min(count, array.Length)).Take(count);
}
private static IEnumerable<T> ShuffleInternal<T>(T[] array, int count)
{
for (var n = 0; n < count; n++)
{
var k = ThreadSafeRandom.Next(n, array.Length);
var temp = array[n];
array[n] = array[k];
array[k] = temp;
}
return array;
}
An implementation of ThreadSafeRandom can be found at the PFX team blog.
这篇关于从集合中随机返回项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!