Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq - advanced .OrderBy

Tags:

c#

linq

c#-4.0

Foo().OrderBy(x=> x.Name)

What if I want the collection to be sorted that way, but exactly one element with Id == (let's say 314) should be always in the beginning, regardless of its name.

like image 399
iLemming Avatar asked Jun 22 '11 20:06

iLemming


3 Answers

You can sort it on two rounds:

Foo().OrderBy(x => x.Id == 314 ? 0 : 1).ThenBy(x => x.Name)

Maybe this is even simpler (assuming boolean false is sported before boolean true)

Foo().OrderBy(x => x.Id != 314).ThenBy(x => x.Name)
like image 50
jishi Avatar answered Oct 18 '22 17:10

jishi


Personally I'd handle that afterwards at the client, but if you'd like a LINQ way, then I would probably avoid Concat - it'll be a more complex query. I'd go for:

int id = 314;
var data = Foo().OrderBy(x => x.Id == id ? 0 : 1).ThenBy(x => x.Name)
like image 27
Marc Gravell Avatar answered Oct 18 '22 17:10

Marc Gravell


Try using Union:

var foo = Foo();
foo.Where(x => x.id == 314).Union(foo.OrderBy(x => x.Name));
like image 1
Platinum Azure Avatar answered Oct 18 '22 17:10

Platinum Azure