How to sort lists using lambda expressions?

Usually I get needed information from SQL server and then do further processing on server side of my web application. Lets say I have a grid of users. Client can sort it by first name or last name, ascending or descending. It is too much typing to create four comparers for Sort method. Luckily you can use lambda expressions. Below is full example:

class Program

{

    static void Main(string[] args)

    {

         List<User> users = new List<User>(new [] {

                new User {FirstName = "Viktar",LastName = "Karpach"},

                new User {FirstName = "Vasya",LastName = "Pupkin"},

                new User {FirstName = "Joe",LastName = "Doe"},

                new User {FirstName = "Jane",LastName = "Doe"}

                                                   });

        Console.WriteLine("Assceding order sorted by first name");

        users.Sort((u1, u2) => string.Compare(u1.FirstName, u2.FirstName, false));

        PrintList(users);

        Console.WriteLine("Descending order sorted by first name");

        users.Sort((u1, u2) => string.Compare(u2.FirstName, u1.FirstName, false));

        PrintList(users);

        Console.WriteLine("Assceding order sorted by last name");

        users.Sort((u1, u2) => string.Compare(u1.LastName, u2.LastName, false));

        PrintList(users);

        Console.WriteLine("Descending order sorted by last name");

        users.Sort((u1, u2) => string.Compare(u2.LastName, u1.LastName, false));

        PrintList(users);

        Console.ReadLine();

    }      

 

    static void PrintList(List<User> users)

    {

        foreach (var user in users)

        {

            Console.WriteLine("{0} {1}",user.FirstName,user.LastName);

        }

    }

}

 

public class User

{

    public string FirstName { get; set; }

    public string LastName { get; set; }

}

 

Results:

Assceding order sorted by first name

  1. Jane Doe
  2. Joe Doe
  3. Vasya Pupkin
  4. Viktar Karpach

Descending order sorted by first name

  1. Viktar Karpach
  2. Vasya Pupkin
  3. Joe Doe
  4. Jane Doe

Assceding order sorted by last name

  1. Joe Doe
  2. Jane Doe
  3. Viktar Karpach
  4. Vasya Pupkin

Descending order sorted by last name

  1. Vasya Pupkin
  2. Viktar Karpach
  3. Joe Doe
  4. Jane Doe

Posted on Wednesday, January 26, 2011 by | Add Comment

New Comment

Your Name:
Email (for internal use only):
Comment:
 
Code above:

Categories

Recent Tweets

  • Simon Ince's Blog: Hierarchies with HierarchyID in SQL 2008 http://t.co/xSDwiF6rRS.
  • Visual Studio 2010 WAS painfully slow - CodeProject http://t.co/Usba1x6CZy

Valid HTML5