Randomise a list of anything in C# with LINQ

///
/// Shuffles the specified list into a random order.
///
/// The type of the list items
/// The list of items.
/// A randomised list of the items.
public static IList Shuffle(this IEnumerable list)
{
    Random rnd = new Random(DateTime.Now.Millisecond);
    var randomised = list.Select(item => new { item, order = rnd.Next() })
        .OrderBy(x => x.order)
        .Select(x => x.item)
        .ToList();

    return randomised;
}

Kevin Wilson

.NET developer, JavaScript enthusiast, Android user, Pebble wearer, sometime musician and occasional cook.

Leave a Reply

Your email address will not be published. Required fields are marked *