Shuffle List in C#


Yesterday, I was looking for an algorithm to shuffle a list of objects in C#. So in my mind, I started to think about "complex" algorithms to do that, using random numbers and list elements switching...

I say "complex" because while I was googling, I found a good solution to do that ! And it takes only 1 line :p I would have never thinked of that :) :)

Here is the cool code:

var shuffledList = myObjectList.OrderBy(item => Guid.NewGuid());

So, that's really simple. You can use the "OrderBy()" Linq extension to rearrange the list. This method will take a 'random' object, in this case a GUID. And we know that GUIDs are 'unique' so, it does the job!

You can use variants like this one:

var rnd = new Random();
var shuffledList = myObjectList.OrderBy(rnd.Next());

Next step, compare performances, between different solutions...


Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard.

1 commentaire: