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