KARPACH

WEB DEVELOPER BLOG

How to sort lists using lambda expressions?

Usually, I get the needed information from SQL server and then do further processing on the server side of my web application. Let’s say I have a grid of users. The client can sort it by first name or last name, ascending or descending. It is too much typing to create four comparers for a Sort method. Luckily you can use lambda expressions. Below is a 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 January 26, 2011 by