Lance Larsen - .NET Architect Madison Wisconsin

Elegantly Randomizing an IEnumerable Collection

Had the need to randomly shuffle an IEnumerable collection that I was bringing back through Entity Framework – so did some searching and came across a couple solutions – some that were completely crazy – but took the best ideas, combined them and then wrapped the final solution into an extension method that I wanted to share. :)  Code is as follows… ( BTW – I love extension methods btw == code & forget )
  

   1:  public static class IenumerableExtensions
   2:  {
   3:      public static IEnumerable<T> Randomize<T>(this IEnumerable<T> enumerable)
   4:      {
   5:          var r = new Random();
   6:          return enumerable.OrderBy(x => r.Next()).ToList();
   7:      }
   8:  }

imageSo just by doing the following:

var widgets = db.Widgets.AsEnumerable().Randomize();

Results are randomized, and it Works Beautifully! 

Wrote the following console app – based on my previous Entity Framework “Code First + Migration” 101 blog article – that shows the Randomize Shuffle – so you can Download and try it for yourself!

Good Coding!

Download Code ( ~2.7M )

 
Comments

No comments yet.

Leave a Reply