Ordering data in LINQ Queries by more than one column.

Posted by vishalneeraj-24503 under LINQ category on | Points: 40 | Views : 393
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 as .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 the same:-
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 we can see in above statement after order by we can add the multiple columns and do the ordering on multiple columns.

Comments or Responses

Login to post response