Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - OrderBy explictly

Tags:

linq

Is it possible to use LINQ OrderBy like so:

.OrderBy(x=>(x.SourceID == 3), (x.SourceID == 2), (x=>x.SourceID == 4), (x.SourceID == 1)).ToList();

So it'll order them by 3, 2, 4, 1 ?

like image 289
CallumVass Avatar asked Mar 06 '26 05:03

CallumVass


1 Answers

No, that is not a valid lambda expression. What you could do instead is something like;

var sortOrder = new List<int> {3, 2, 4, 1};
var result = bop.OrderBy(x=> sortOrder.IndexOf(x.SourceID)).ToList();

If you want to extend this to doing special things with unknowns (they end up first now), you can just make a method that makes the determination of the sort order and use that instead.

like image 124
Joachim Isaksson Avatar answered Mar 08 '26 07:03

Joachim Isaksson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!