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().
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…
Clever!
Hello, I really admire the look of your site. What template are you using?
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
Really good post! I’ve bookmarked your web site as well considering I discovered it is truly educational and I enjoyed reading your posts.
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.
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