Search code examples
.netlinqenumerable

Order a Collection by a List<int>


I have a Collection of Products. Each product has a ProductId (int) property. I also have a List<int> with one entry for each ProductId. I need to order by Collection<Products> by the List<int>. Is this possible using LINQ or some other method?


Solution

  • Try this:

    var res = orig.OrderBy(p => orderSettingList.IndexOf(p.ProductId));
    

    Note that the products the value of the property for which are not in the list will sort ahead of all other products.