Dmitry O
Dmitry O

Reputation: 181

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?

Upvotes: 10

Views: 4699

Answers (1)

George Johnston
George Johnston

Reputation: 32258

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

Upvotes: 25

Related Questions