Ordering data in LINQ Queries by more than one column
Join the DZone community and get the full member experience.Join For Free
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
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;
Published at DZone with permission of Pranay Rana, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.