Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Let's randomize IEnumerable

4.75/5 (4 votes)
9 Oct 2011CPOL 26.5K  
I needed to randomize a collection. Here's my solution.
I needed to randomize an enumerable collection. Here's what I came up with in the 60 seconds I thought it deserved.

Your challenge:

  1. Do it better. better = faster with same number of items and/or faster with n items.

  2. Prove it.

C#
using System;
using System.Collections.Generic;

/// <summary>
/// Extension class for IEnumerable&lt;T&gt;
/// </summary>
static class IEnumerableExtension
{
    /// <summary>
    /// Randomizes the specified collection.
    /// </summary>
    /// <typeparam name="T">The type of the collection.</typeparam>
    /// <param name="collection">The collection.</param>
    /// <returns>The randomized collection</returns>
    public static IEnumerable<T> Randomize<T>(this IEnumerable<T> collection)
    {
        // Put all items into a list.
        var list = new List<T>(collection);
        var randomizer = new Random();
        // And pluck them out randomly.
        for (int i = list.Count; i > 0; i--)
        {
            int r = randomizer.Next(0, i);
            yield return list[r];
            list.RemoveAt(r);
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)