ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Shuffle

Shuffles an IEnumerable list

Source

public static IEnumerable<T> Shuffle<T>(this Enumerable<T> list) 
{
    var r = new Random((int)DateTime.Now.Ticks);
    var shuffledList = list.Select(x => new { Number = r.Next(), Item = x }).OrderBy(x => x.Number).Select(x => x.Item);
    return shuffledList.ToList();
}

Example

var names = new List<string>();
names.Add("Harry");
names.Add("Dick");
names.Add("Tom");
var namesShuffled = names.Shuffle();

Author: Wes Caldwell

Submitted on: 13 jul. 2009

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 12263