iLemming
iLemming

Reputation: 36166

Linq - advanced .OrderBy

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

Answers (3)

Marc Gravell
Marc Gravell

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

Platinum Azure
Platinum Azure

Reputation: 46183

Try using Union:

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

Upvotes: 1

jishi
jishi

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

Related Questions