Over a million developers have joined DZone.

Ordering data in LINQ Queries by more than one column

DZone's Guide to

Ordering data in LINQ Queries by more than one column

Free Resource
In this post I am going to show how to do ordering when you require to order data by using the multiple columns.

By using .Orderby(x=>x.Columnname) in the LINQ query we can easily order data of the source collection. So most of new developer make use of the same function two time  .Orderby(x=>x.Columnname).Orderby(x=>x.Columnname) and thinks that will do the ordering on the multiple columns.
IEnumerable<Employee> emp = dc.Employees
                                 .OrderBy(x => x.Name)
                                 .OrderBy(x => x.Desc); 

But its always does the order by the column you specified in the last OrderBy() method.

Following is two solution to achieve
Solution 1:
Always make use of  ThenBy() after  OrderBy() because   OrderBy() returns an IOrderedEnumerable which then exposes the Methods: ThenBy() and ThenByDescending(). This means that we can OrderBy on multiple Fields by chaining the OrderBy() and ThenBy() together.
IEnumerable<Employee> emp = dc.Employees
                                  .ThenBy(x =< x.Name)
                                  .OrderBy(x => x.Desc);

Solution 2:
If you don't want to go for the Lamda expression where you can easily achieve the multiple ordering
var emp = from e in dc.Employees
          orderby e.Name, e.Desc
          select e;
As you can see in above statement after order by you can add the multiple columns and do the ordering on multiple columns.

Published at DZone with permission of Pranay Rana, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}