0

I have a list of objects that I want to randomly arrange or jumble up. Is this possible? The list is built up from company products. I take the top 2 of each company and the add the rest to another list. I want to jumble the second list.

Thanks for any help


Try this:

var rnd = new Random();
var shuffledList = list.OrderBy(x => rnd.Next()).ToList();

This works fine, because OrderBy implementation first creates a list of keys and then sorts using the generated keys. So the lamba expression is only called once for each item. During the sort processes, each item in the list has it's own, random sort key.

4

3 回答 3

5

尝试这个:

var rnd = new Random();
var shuffledList = list.OrderBy(x => rnd.Next()).ToList();

这很好用,因为 OrderBy 实现首先创建一个键列表,然后使用生成的键进行排序。因此,lamba 表达式仅对每个项目调用一次。在排序过程中,列表中的每个项目都有自己的随机排序键。

于 2012-07-23T11:43:30.047 回答
1

You don't need O(N*LogN) operation. Just use FisherYatesShuffle

See Also: http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

于 2012-07-23T12:06:38.897 回答
1

Try NBuilder - it builds lists of objects, and provides inclemently generated values for properties (you also can provide any value manually):

var products = Builder<Product>.CreateListOfSize(10).Build();

If you want (non-incremental) random items, you can pick them from any collection:

var randomProducts = Pick<Product>.UniqueRandomList(3).From(products);
于 2012-07-23T12:21:37.410 回答