Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort collection within collection using Linq

Tags:

c#

linq

I have a one-to-many Linq query and I would like to sort on a property within the "many" collection. For example in the pseudo-code below, I am returned a List from the 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;
}
like image 632
HBCondo Avatar asked Apr 27 '10 16:04

HBCondo


2 Answers

order.Product.OrderBy(p => p.SequenceNumber);
like image 165
Andrey Avatar answered Nov 03 '22 15:11

Andrey


As I read your question, your query returns IEnumerable<Order> and you want to sort them on SequenceNumber.

In order to sort on something, it must have one value. There are multiple SequenceNumber's because there are multiple Products. You need to decide how you will select the number to sort on.

Let's say you want to sort the orders on the largest SequenceNumber for Products on that Order. Then a query could be:

from order in orders
orderby order.Products.Max(p=>p.SequenceNumber)
select order;
like image 45
driis Avatar answered Nov 03 '22 13:11

driis