Reputation: 11458
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 ?
Upvotes: 3
Views: 321
Reputation: 674
Taking Joachim Isaksson's answer above, this could be wrapped in an extension method:
public static class ListExtensions
{
public static List<Source> SortByCustomOrder(this List<Source> list, List<int> sortOrder)
{
return list.OrderBy(x => sortOrder.IndexOf(x.SourceId)).ToList();
}
}
replacing Source with your Class and x.SourceId with your property
Usage:
// the sort order
var sortOrder = new List<int> { 3, 2, 4, 1, 6, 5 };
var results = sources.SortByCustomOrder(sortOrder);
Upvotes: 2
Reputation: 181077
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.
Upvotes: 7