65.9K
CodeProject is changing. Read more.
Home

Let's randomize IEnumerable

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.48/5 (7 votes)

Oct 11, 2011

CPOL
viewsIcon

16941

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.