IEnumerable.Shuffle Implementation

Following code is an implementation of Shuffle method on IEnumerable based on the Durstenfeld modification of Fisher Yates Shuffle algorithm, a simple and efficient method.

public static IEnumerable<TSource> Shuffle<TSource>(this IEnumerable<TSource> dataArray)
{
    var dataArrayList = dataArray.ToList();
    var returnValue = Enumerable.Empty<TSource>();
    for (int index = dataArrayList.Count()-1; index > 0; index--)
    {
        var randomKey = _randomGenerator.Next(1, index);
        var temp = dataArrayList[randomKey];
        dataArrayList[randomKey] = dataArrayList[dataArray.Count() - 1];
        dataArrayList[dataArray.Count() - 1] = temp;
    }
    return dataArrayList;
}

More information on the algorithm can be found in Wiki.

The complete code can be found in Github

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s