LINQ to Entities - multiple OrderBy methods do not work
-
If I apply 2 OrderBy methods to my query, like that
query.OrderBy(rec => rec.Name).OrderByDescending(rec => rec.Title);
then only second method is applied, the first one is ignored. Is it a bug? What if I need to have ascending ordering for one column and descending ordering for another? Is it not achievable at all by method syntax?
-
If I apply 2 OrderBy methods to my query, like that
query.OrderBy(rec => rec.Name).OrderByDescending(rec => rec.Title);
then only second method is applied, the first one is ignored. Is it a bug? What if I need to have ascending ordering for one column and descending ordering for another? Is it not achievable at all by method syntax?
There isn't a "bug" as such, the framework is written that way, but anyone would expect your code to be the syntax used . Instead, you should use this [less clear!] code:
query.OrderBy(rec => rec.Name).ThenByDescending(rec => rec.Title);
If you want to add another order by ascending just use
.ThenBy
instead.Sort of a cross between Lawrence of Arabia and Dilbert.[^]
-Or-
A Dead ringer for Kate Winslett[^] -
If I apply 2 OrderBy methods to my query, like that
query.OrderBy(rec => rec.Name).OrderByDescending(rec => rec.Title);
then only second method is applied, the first one is ignored. Is it a bug? What if I need to have ascending ordering for one column and descending ordering for another? Is it not achievable at all by method syntax?
No its not a bug, its performing exactly as you have requested. Looking at the documentation you can see what is happening. OrderByDecending[^]: "Sorts the elements of a sequence in descending order according to a key." ThenByDescending[^]: "Performs a subsequent ordering of the elements in a sequence in descending order, according to a key." Notice the latter says a subsequent ordering.
I know the language. I've read a book. - _Madmatt
-
If I apply 2 OrderBy methods to my query, like that
query.OrderBy(rec => rec.Name).OrderByDescending(rec => rec.Title);
then only second method is applied, the first one is ignored. Is it a bug? What if I need to have ascending ordering for one column and descending ordering for another? Is it not achievable at all by method syntax?
OK, thanks for explanation!