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
- Jane Doe
- Joe Doe
- Vasya Pupkin
- Viktar Karpach
Descending order sorted by first name
- Viktar Karpach
- Vasya Pupkin
- Joe Doe
- Jane Doe
Assceding order sorted by last name
- Joe Doe
- Jane Doe
- Viktar Karpach
- Vasya Pupkin
Descending order sorted by last name
- Vasya Pupkin
- Viktar Karpach
- Joe Doe
- Jane Doe
Posted on January 26, 2011 by Viktar Karpach