Sorting a collection into collections using Linq

I have a one-to-many Linq query, and I would like to sort by property in the "many" collection. For example, in the pseudo code below, I get a list from a Linq query, but I would like to sort / order the Products property based on the SequenceNumber property of the Product class. How can i do this? Any information is appreciated. Thanks.

public class Order { public int OrderId; public List<Product> Products; } public class Product { public string name; public int SequenceNumber; } 
+6
c # linq
source share
4 answers
 order.Product.OrderBy(p => p.SequenceNumber); 
+4
source share

When I read your question, your query will return an IEnumerable <Order> and you want to sort them by SequenceNumber.

To sort something, it must have one value. There are several SequenceNumber because there are several products. You need to decide how to choose the number to sort.

Suppose you want to sort orders at the largest SequenceNumber for the products of this order. Then the request could be:

 from order in orders orderby order.Products.Max(p=>p.SequenceNumber) select order; 
+4
source share

Inside Order just do

 Products = Products.OrderBy(o => o.SequenceNumber); 

In List<T> there is a Sort() method to sort the list.

+2
source share

If you want to sort the collection "in place", just call

 Products.Sort((lhs, rhs) => lhs.SequenceNumber.CompareTo(rhs.SequenceNumber)); 

If you want to sort the collection "on demand" just use LINQ:

 foreach (var product in order.Products.OrderBy(x => x.SequenceNumber)) { } 
+2
source share

All Articles