65.9K
CodeProject is changing. Read more.
Home

Let's randomize IEnumerable

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.75/5 (4 votes)

Oct 9, 2011

CPOL
viewsIcon

26453

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.
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);
        }
    }
}