Random Sort a List Using LINQ

LINQ (Language Integrated Query) is a one of very useful feature of .net 3.5 framework. This allows you to query objects and perform complex operations simply and efficiently. There are lots of trick which can be used with the help of LINQ. In this article I am explaining how can we random sort a List using LINQ

Random Sort

Consider the below Employee class:

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

This is how you can randomly sort the List<Employee> object:

List<Employee> list = new List<Employee>();

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

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

10 comment(S)


Darmidont on Dec 30, 2008 04:00 AM

thanks!

Visual C# Kicks on Jan 16, 2009 12:01 AM

That's definitely better than the old way of doing things:
http://www.vcskicks.com/randomize_array.html

Patrick on Apr 15, 2009 11:57 AM

Great example...

Jack on Sep 6, 2009 10:33 PM

only a IList variable can perform the OrderBy method like this, the one of IQueryble,or IEnumarable can not. see http://jack-fx.com/blog/c-and-net/

Rahul Chitte on Jul 6, 2010 12:07 AM

Cool example...
Can we sort the list in ascending or descending manner?

Emmanuel on Apr 17, 2012 05:18 PM

Nice..

Rich on Oct 11, 2012 06:21 PM

That's genius. Thanks.

cizgifilm1.com on Nov 7, 2012 07:41 AM

very good. Thanks

Alex Peter on Dec 2, 2012 05:51 AM

This is not the right way of doing it. Guid.NewGuid() does not give random numbers at all. Every GUID is unique but not random. If you execute several Guid.NewGuid() you will see that each GUID is unique but together they cannot pass even the simplest random test. Use this better

Random rnd = new Random();
list = list.OrderBy(emp => rnd.Next()).ToList();

sponsored

Vivek Gupta on Apr 7, 2014 09:51 PM

Nice yaaar

Leave a comment