Linq order by Area Name with one exception
Hi say I have objects of type Area with Names:
Hokitika Dunedin开发者_开发知识库 Stewart Island West Coast Invercargill
and I want to order them by name I could go:
areas.OrderBy(a => a.Name)
to give me:
Dunedin Hokitika Invercargill Stewart Island West Coast
which is fine but what say I was wanting to make this to be an ordered list with the exception that the current users location was at the top so if they were in Invercargill the list would be:
Invercargill Dunedin Hokitika Stewart Island West Coast
Is this possible in Linq?
Sure. You can order by a bool:
areas.OrderByDescending(a => a.Equals(myArea, StringComparison.OrdinalIgnoreCase))
.ThenBy(a => a.Name);
If that doesn't work on your DB, you can try:
areas.Select(a => new { IsMyLocation = a.Equals(myArea, StringComparison.OrdinalIgnoreCase),
Area = a })
.OrderByDescending (a => a.IsMyLocation)
.Select(a => a.Area);
string currentLocation = "Invercatgill"; // for instance
var sortedresult = areas.OrderBy(a => a.Name.Equals(currentLocation) ? 0 : 1)
.ThenBy(a => a.Name);
Just another way to do it using Except
var currentLocation = new [] { user.CurrentLocation };
var otherAreas = areas.Except(currentLocation).OrderBy(x => x.Name)
var finalResult = currentLocation.Concat(otherAreas);
精彩评论