Pages

Thursday, January 14, 2010

Randomize a List<T>

Here's another instalment in a sporadic series of useful C# extension methods. This time we return a List in a random order:

public static class ICollectionExtensions
{
/// <summary>
/// Randomizes the specified source.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param>
/// <returns></returns>
public static ICollection<T> Randomize(this ICollection<T> source)
{
Random rng = new Random();

T[] a = new T[source.Count];
source.CopyTo(a, 0);

byte[] b = new byte[a.Length];
rng.NextBytes(b);

Array.Sort(b, a);

return new List<T>(a);
}
}

No comments: