Tip: random sort order in C#

I wanted to randomize the display of a List on my site — meaning I would retrieve (say) 20 records, but display only 5, chosen at random. I was imagining a loop that generates a bunch of random indexes, which I use to individually pull elements from the list. Yuck.

The solution I found is much more elegant — two lines! To randomize your list, simply: var rnd = new Random();
myList = myList.OrderBy(x => rnd.Next()).ToList();

To take n random elements: var rnd = new Random();
myList = myList.OrderBy(x => rnd.Next()).Take(n).ToList();

If you’d like to encapsulate it, you might use extension methods: public static IEnumerable<T> OrderByRandom<T>(this IEnumerable<T> source)
{
var rnd = new Random();
return source.OrderBy(x => rnd.Next());
}

public static IEnumerable<T> TakeRandom<T>(this IEnumerable<T> source, int n)
{
return source.OrderByRandom().Take(n);
}

Hope this helps.

Note: be careful with IEnumerable here — because it behaves lazily, it can cause the randomization to happen multiple times, depending on how you call it. Better to “realize” it using ToList().

Published April 28, 2010