Let's randomize IEnumerable






3.48/5 (7 votes)
I was actually going to suggest a simpler version of cechode's version, but along the same lines.public static IEnumerable Randomize(this IEnumerable source){ Random r = new Random(); return source.Select(x => new { Key = r.Next(), Value = x }) .OrderBy(x => x.Key) ...
I was actually going to suggest a simpler version of cechode's version, but along the same lines.
public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
{
Random r = new Random();
return source.Select(x => new { Key = r.Next(), Value = x })
.OrderBy(x => x.Key)
.Select(x => x.Value);
}
Edit: In response to http://blogs.msdn.com/b/ericlippert/archive/2011/01/31/spot-the-defect-bad-comparisons-part-four.aspx[^], I've updated it to generate a single random number to sort upon.