Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Let's randomize IEnumerable

3.48/5 (7 votes)
12 Oct 2011CPOL 16.9K  
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.
C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)