LINQ, OrderBy() and ThenBy()

LinQ is the magic technique behind querying a list in C# .Net and it is easier to use and a cleaner way of querying a list. This is one of the small tips that make a huge difference and save your time.

What is the scenario ?

Assume that you have a list of customer objects which you want to order by the first name and then item order date. How are you going to do that with LINQ? Is there any easy method in Linq?

What we know ?

We are familiar with below two ways of sorting a list in ascending or descending order.

var ascendingOrderdList = ListOfItems.OrderBy(x=>x.Property); -  Order by ascending
var descendingOrderdList = ListOfItems.OrderByDescending(x=> x. Property); – Order by descending

Solution to order more than once ?

To solve, you can associate ThenBy() with OrderBy() and OrderByDescending() in LINQ

var orderdList = ListOfItems.(x=>x.PropertyA).ThenBy(x=>x.PropertyB);

Example Code


Happy coding guys!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s