Today , i was required to order a list of records based on a Name and then ID .
A simple one but i did spend some time on how to do it with Lambda Expression in C# .
C# provides the OrderBy,OrderByDescending,ThenBy,ThenByDescending .
You can use them in your lambda expression to order the records as per your requirement .
Assuming your list is “Phones” and contains the following data …
public class Phone
{
public int ID { get; set; }
public string Name { get; set; }
}
public class Phones : List
{
public Phones()
{
Add(new Phone { ID = 1, Name = "Windows Phone 7" });
Add(new Phone { ID = 5, Name = "iPhone" });
Add(new Phone { ID = 2, Name = "Windows Phone 7" });
Add(new Phone { ID = 3, Name = "Windows Mobile 6.1" });
Add(new Phone { ID = 6, Name = "Android" });
Add(new Phone { ID = 10, Name = "BlackBerry" });
}
}
If you were to use LINQ Query , the query will look like the one below
dataGridView1.DataSource = (from m in new Phones()
orderby m.Name, m.ID
select m).ToList();
Simple isn’t it ? It very simple using Lamba expression too
Your Lambda’s expression for the above LINQ query will look like the one below
dataGridView1.DataSource = new Phones().OrderByDescending(a => a.Name).ThenByDescending(a => a.ID).ToList();


4 comments
How to order by multiple columns using Lambas... | .NET, C# | Syngu
[...] How to order by multiple columns using Lambas and LINQ in C# ? Today , i was required to order a list of records based on a Name and then ID . A simple one but i did spend some time on how to do it with Lambda Expression in C# . C .NET, C# Read the original post on DotNetShoutout… [...]
Dec 24, 2011
How to order by multiple columns using Lambas... | Microsoft | Syngu
[...] How to order by multiple columns using Lambas and LINQ in C# ? Today , i was required to order a list of records based on a Name and then ID . A simple one but i did spend some time on how to do it with Lambda Expression in C# . C Microsoft Read the original post on DZone… [...]
Dec 25, 2011
Interesting .NET Linke - December 27 , 2011 | Tech Blog
[...] How to order by multiple columns using Lambas and LINQ in C# ? [...]
Dec 27, 2011
Lawrance
this was very helpful. keep up the goodwork.
Jan 13, 2012