In this post I’ll show how you can apply ordering on
the multiple columns in LINQ query.
If you know LINQ basics, you must be aware that with
the help of .OrderBy(x
=> x.Columnname) in the LINQ query we can order
data of the source collection.
So many of the novice developers use the same
function twice as mentioned below and thinks that will do the ordering on the
multiple columns.
var students = context.Students
.OrderBy(x => x.Name)
.OrderBy(x =>
x.ClassName);
|
But that is not the solution and LINQ query always
does the order by the column you specified in the last OrderBy() method.
We can do order by on more than one columns using lambda
expressions as well as in traditional LINQ query.
Mentioned below are two solutions to achieve using
Lambda and traditional LINQ queries:
Using Lambda Expression:
Change above mentioned query to following to
make it work:
var students = context.Students
.OrderBy(x => x.Name)
.ThenBy(x => x.ClassName);
|
One important thing to remember is always make use
of ThenBy() after OrderBy() because OrderBy() returns an IOrderedEnumerable which
then exposes the Methods: ThenBy() and ThenByDescending().
Using traditional LINQ Query:
If you are traditional LINQ query writer and don’t
want to use the lambda expression, then you can do ordering on multiple columns
with following way:
var students = from s in context.Students
orderby s.Name, s.ClassName
select s;
|
Hope that helps !!!
Comments
Post a Comment