Reputation: 36166
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.
Upvotes: 7
Views: 3797
Reputation: 1062590
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)
Upvotes: 3
Reputation: 46183
Try using Union
:
var foo = Foo();
foo.Where(x => x.id == 314).Union(foo.OrderBy(x => x.Name));
Upvotes: 1
Reputation: 24614
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)
Upvotes: 21