Linq - Advanced .OrderBy

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

What should I do if I want the collection to be sorted this way, but exactly one element with Id == (for example, 314) should always be at the beginning, regardless of its name.

+7
source share
3 answers

You can sort it in two rounds:

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

Perhaps this is even simpler (assuming boolean false is set to boolean true)

 Foo().OrderBy(x => x.Id != 314).ThenBy(x => x.Name) 
+21
source

Personally, I would process this later on the client, but if you want to use the LINQ method, then probably I would avoid Concat - this will be a more complex request. I would go for:

 int id = 314; var data = Foo().OrderBy(x => x.Id == id ? 0 : 1).ThenBy(x => x.Name) 
+3
source

Try using Union :

 var foo = Foo(); foo.Where(x => x.id == 314).Union(foo.OrderBy(x => x.Name)); 
+1
source

All Articles