What is wrong with OrderBy Linq Extension in EF4?
I have following two calls, both are same but results are different...
I开发者_如何学JAVAt 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?
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)
Change the second OrderBy to ThenBy.
精彩评论