Home > C#, Linq > Extension method fun 2

Extension method fun 2

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)
        Console.WriteLine(item);
}
Categories: C#, Linq
  1. January 16, 2011 at 04:59

    Most what i read online is trash and copy paste but i think you offer something different. Keep it like this.

  1. No trackbacks yet.

Leave a comment