Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to Entities - multiple OrderBy methods do not work

If I apply two 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?

like image 618
Dmitry O Avatar asked Jan 14 '11 17:01

Dmitry O


1 Answers

Try this:

query.OrderBy(rec => rec.Name).ThenByDescending(rec => rec.Title);

Your second OrderBy is reseting your first result set. That's why the ThenBy extension exists. It will preserve your first result set, while applying additional sorting to it.

Essentially, your existing solution as psuedo SQL would look something like this:

results = SELECT * FROM Obj ORDER BY Name;
results = SELECT * FROM results ORDER BY Title DESC;

...which isn't what you want. The ThenBy extension would look something like this:

results = SELECT * FROM Obj ORDER BY Name ASC, Title DESC
like image 185
George Johnston Avatar answered Sep 20 '22 00:09

George Johnston