Search 
DailyCoding > General

Random Sort a List Using LINQ

How to random Sort a List by using simple LINQ technique
Author admin on Nov 21, 2008 4 Comments
Rate it    (Rated 3 by 10 people)
3,796 Views

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();
C# | Utility

Discussion

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/

Leave a Comment

Name
Email Address
Web Site
© Copyright 2008 Daily Coding • All rights reserved