Akash Kava
Akash Kava

Reputation: 39916

What is wrong with OrderBy Linq Extension in EF4?

I have following two calls, both are same but results are different...

It is simple console application with connection to local database.

DBContext db = new DBContext();

This one sorts as expected,

var q = from x in db.Cities
        orderby x.CountryCode, x.City
        select x;

foreach(var x in q){
   Console.WriteLine("{0}:{1}",x.CountryCode, x.City);
}

But why this one does not sort by City, it only sorts by CountryCode

foreach(var x in db.Cities.OrderBy(d=>d.City).OrderBy(d=>d.CountryCode)){
   Console.WriteLine("{0}:{1}",x.CountryCode, x.City);
}

If I change order of OrderBy statements, then only Last OrderBy seem to work correctly but intermediate OrderBy has no impact at all. Is this bug in EF or Linq extensions?

I have no problem in rewriting queries but I want to know what is wrong with OrderBy Linq Extension method?

Upvotes: 0

Views: 445

Answers (2)

Hans Kesting
Hans Kesting

Reputation: 39284

Change the second OrderBy to ThenBy.

Upvotes: 1

Kristof Claes
Kristof Claes

Reputation: 10941

I have a blog post about this: http://www.kristofclaes.be/blog/2010/07/06/order-on-multiple-fields-with-linq/

The problem is that the second OrderBy() overrules the first one. To fix this, you can replace the second OrderBy() with ThenBy() like this:

db.Cities.OrderBy(d=>d.City).ThenBy(d=>d.CountryCode)

Upvotes: 4

Related Questions