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,…
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 )
public static class IenumerableExtensions
{
public static IEnumerable<T> Randomize<T>(this IEnumerable<T> enumerable)
{
var r = new Random();
return enumerable.OrderBy(x => r.Next()).ToList();
}
}
So 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 )