Web developers wiki ASP.NET Sitecore Sharepoint Kentico by Evident Interactive

Random sort order in C# or LINQ

Modified: 2009/08/14 13:41 by arjan - Categorized as: ASP.NET


Here is a code snippet to sort a C# generic List in random order:

C#:
Random rnd = new Random();
items.Sort(delegate(Item item1, Item item2) { return ((item1 == item2) ? 0 : rnd.Next(-1, 1)); });

Or if you like LINQ:

C#:
Random rnd = new Random(); 
var result = from item in Items 
             orderby rnd.Next() 
             select item;

 © Evident Interactive BV