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.
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)
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)
Try using Union
:
var foo = Foo();
foo.Where(x => x.id == 314).Union(foo.OrderBy(x => x.Name));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With