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

AksharRoop
  • 2,263
  • 1
  • 19
  • 29
Wesley Skeen
  • 7,977
  • 13
  • 42
  • 56
  • 1
    This question may help: http://stackoverflow.com/questions/5807128/an-extension-method-on-ienumerable-needed-for-shuffling – Tharwen Jul 23 '12 at 11:40
  • Some good answers [here](http://stackoverflow.com/questions/375351/most-efficient-way-to-randomly-sort-shuffle-a-list-of-integers-in-c-sharp) – Bali C Jul 23 '12 at 11:40
  • 2
    http://www.dotnetperls.com/fisher-yates-shuffle – Tim Schmelter Jul 23 '12 at 11:42
  • Have you had a look into any of these?http://stackoverflow.com/questions/tagged/c%23+shuffle – AksharRoop Jul 23 '12 at 11:58
  • @TimSchmelter: Thanks, did not know the name for it. Explained the same process in an interview once, and the interviewer seemed to think my approach was 'interesting'. They also declined me as I was not 'strong' as another candidate. I did not even lift a weight! – leppie Jul 23 '12 at 11:59

3 Answers3

5

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.

Carsten Schütte
  • 4,408
  • 1
  • 20
  • 24
  • That can make problems for the OrderBy method when comparing same objects can produce different results. – Tomas Grosup Jul 23 '12 at 11:46
  • @Tomas: No, you're wrong. Take a look at OrderBy implementation: class System.Linq.EnumerableSorter, method Sort. I've added a sentence about that to my answer. – Carsten Schütte Jul 23 '12 at 11:53
  • https://blogs.msdn.microsoft.com/ericlippert/2011/01/31/spot-the-defect-bad-comparisons-part-four/ explains why this can crash – marczellm May 26 '16 at 16:03
1

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

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

Community
  • 1
  • 1
L.B
  • 114,136
  • 19
  • 178
  • 224
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);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459