Thursday, 26 August 2010

Randomly sort a list using LINQ

This is far neater than the loop and temporary list I had in mind. Two lines of code!
Random rnd = new Random();
myList = myList.OrderBy(x => rnd.Next()).ToList();
Or, to take n random elements from a list:
Random rnd = new Random(); 
myList = myList.OrderBy(x => rnd.Next()).Take(n).ToList();

No comments:

Post a Comment

Comments are moderated, so you'll have to wait a little bit before they appear!