Let's randomize IEnumerable






4.75/5 (4 votes)
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:
- Do it better. better = faster with same number of items and/or faster with
n
items. - Prove it.
using System;
using System.Collections.Generic;
/// <summary>
/// Extension class for IEnumerable<T>
/// </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);
}
}
}