Apr 17, 2013 LANCE LARSEN
NEXT

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();
    }
}

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 )

NEXT
[ SYSTEM ] Rejoining the server...
[ WARNING ] Rejoin failed... trying again in seconds.
[ CRITICAL ] Failed to rejoin. Please retry or reload the page.
[ PAUSED ] The session has been paused by the server.
[ CRITICAL ] Failed to resume the session. Please retry or reload the page.

RECONNECTING

NEURAL_LINK_LOST

Stream has been de-synced
or shifted to a restricted sector.
Attempting to re-establish connection...