Solving development problems  |  About this blog

Archive for the ‘random sorting’ tag

Random sorting using LINQ

Random Sort

Consider the below Person class:

public class Person
{
    public int Id
    {
        get;
        set;
    }
    public string Name
    {
        get;
        set;
    }
}

This is how you can randomly sort the List object:

List list = new List();

list.Add(new Person { Id = 1, Name = "Davolio Nancy" });
list.Add(new Person { Id = 2, Name = "Fuller Andrew" });
list.Add(new Person { Id = 3, Name = "Leverling Janet" });
list.Add(new Person { Id = 4, Name = "Peacock Margaret" });
list.Add(new Person { Id = 5, Name = "Buchanan Steven" });
list.Add(new Person { Id = 6, Name = "Suyama Michael" });
list.Add(new Person { Id = 7, Name = "King Robert" });
list.Add(new Person { Id = 8, Name = "Callahan Laura" });
list.Add(new Person { Id = 9, Name = "Dodsworth Anne" });

list = list.OrderBy(x => Guid.NewGuid()).ToList();

Or you can use this approach:

Random random = new Random();
list = (from x in list
       let r = random.Next()
       orderby r
       select x).ToList();

Written by Avivo

July 15th, 2010 at 10:07 am