tags:

views:

109

answers:

5

Hi, 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;
}
+2  A: 

Within Order, simply do

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

There is also a Sort() method within List<T> to sort the list directly.

BlueRaja - Danny Pflughoeft
"pseudo-code below"
Andrey
sorry, i updated the pseudo-code in my original post to include the accessors (everything is public)
+2  A: 
order.Product.OrderBy(p => p.SequenceNumber);
Andrey
A: 

Read about order by clause.

danish
+1  A: 

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;
driis
i like this approach b/c it allows the sorting within the linq query itself. however, i receive a Member access 'Int32 SequenceNumber' not legal error when trying to do this.
A: 

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)) {
}
Brannon