Archive for the ‘Linq’ Category

Extension method fun 2

January 2, 2011 1 comment

Sometimes it is required to shuffle the elements of a collection. I have seen little algorithm monsters that did this, yet it can be done in c# and .Net in a very clean way using a Linq query. The key to understand my Linq query, is knowing that the orderby expression does not necessarily has to order the elements of your query.

public static class EnumerableExtensions
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> enumerable)
         return from i in enumerable
                orderby Guid.NewGuid()
                select i;

A small test application:

static void Main(string[] args)
    List<string> inputData = new List<string>() { "pieter", "bill", "steve" };
    IEnumerable<string> shuffledData = inputData.Shuffle();

    foreach (string item in shuffledData)
Categories: C#, Linq