Tip: random sort order in C#

I wanted to randomize the display of a List on my site – meaning I would retrieve (say) 20 records, but display only 5, chosen at random. I was imagining a loop that generates a bunch of random indexes, which I use to individually pull elements from the list. Yuck.

The solution I found is much more elegant – two lines! To randomize your list, simply:

var rnd = new Random();
myList = myList.OrderBy(x => rnd.Next()).ToList();

To take n random elements:

var rnd = new Random();
myList = myList.OrderBy(x => rnd.Next()).Take(n).ToList();

If you’d like to encapsulate it, you might use extension methods:

public static IEnumerable<T> OrderByRandom<T>(this IEnumerable<T> source)
{
   var rnd = new Random();
   return source.OrderBy(x => rnd.Next());
}

public static IEnumerable<T> TakeRandom<T>(this IEnumerable<T> source, int n)
{
   return source.OrderByRandom().Take(n);
}

Hope this helps.

Note: be careful with IEnumerable here – because it behaves lazily, it can cause the randomization to happen multiple times, depending on how you call it. Better to “realize” it using ToList().

This entry was posted in Uncategorized. Bookmark the permalink.

7 Responses to Tip: random sort order in C#

  1. Mister Bytes says:

    Hey Matt,

    Nice! For generating random links for end cards on Glo I used the NewGuid() lambda approach:

    randList = randList.OrderBy(v => Guid.NewGuid()).ToList(); //randomize the result set
    randList = randList.Take(5).ToList(); //grab the top count…

  2. Hue Ruggero says:

    Hello, I really admire the look of your site. What template are you using?

  3. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

  4. Really good post! I’ve bookmarked your web site as well considering I discovered it is truly educational and I enjoyed reading your posts.

  5. Wow, marvelous posting! Kudos for posting. I do have a couple questions for you, so I’ll look for your email and email them directly if that’s okay.

  6. Hi Matt,
    Very useful your tips. Congrats!
    Please, a simple doubt… My tests fail because doesn´t recognize “OrderBy”, could you clarify this point?
    Thanks, best
    Daniel

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s