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);
}
Advertisements
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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: