Randomizing a list with LINQ

There are many ways to randomize a list; perhaps the most common is to simply iterate over the list and swap each element with a random other element. Some libraries even include built-in methods for randomizing a list, but .Net isn’t one of those.

The introduction of LINQ in .Net 3.5 provides an easy way to manipulate lists and collections in all sorts of ways. So naturally one question that may come up is, can we use it to randomize a list? The answer is yes, you can. There’s probably more than one way to do it, but here’s one I like myself.

Random rnd = new Random();
var randomizedList = from item in list
                     orderby rnd.Next()
                     select item;

The orderby clause will use the specified expression to compare elements to determine their order. Here, it is using random values to do that comparison, so the end result is a randomized list.

Of course we can easily create an extension method to make things even easier (here I use an alternative syntax to use orderby, just to demonstrate how to do it with that):

public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
{
    Random rnd = new Random();
    return source.OrderBy<T, int>((item) => rnd.Next());
}

Categories: Programming
Posted on: 2009-01-16 14:12 UTC.

Comments

Ion Todirel

2009-03-01 00:22 UTC

var res =
from item in list
orderby Guid.NewGuid()
select item;

cizgifilm1

2012-11-07 14:40 UTC

Veryy good.

Add comment

Latest posts

Categories

Archive

Syndication

RSS Subscribe