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
3: public static IEnumerable<T> Randomize<T>(this IEnumerable<T> enumerable)
5: var r = new Random();
6: return enumerable.OrderBy(x => r.Next()).ToList();
var widgets = db.Widgets.AsEnumerable().Randomize();
Results are randomized, and it Works Beautifully!
Download Code ( ~2.7M )