16

Possible Duplicate:
Multiple “order by” in LINQ

I have a list of orders and I need to order it by the date of the order and then a secondary sort by the price of the order. I'm not sure how exactly to do this since I tried orders.OrderBy(o => o.Date).OrderBy(o => o.Price), but it doesn't work. Any help is much appreciated. Thank you

4
  • 2
    its weird how many of this exact same question I've seen today. Commented Aug 3, 2012 at 15:23
  • I don't mean to be rude but I just googled Ordering linq query with secondary sort and found the answer on the first page to a SO post. Commented Aug 3, 2012 at 15:25
  • 2
    actually, its a duplicate of this, this, this, this,this,this, etc Commented Aug 3, 2012 at 15:27
  • Sorry, I'm new to this site... tried to find it but I missed it. Thanks. Commented Aug 3, 2012 at 16:47

3 Answers 3

35

You want to use the ThenBy function:

orders.OrderBy(o => o.Date).ThenBy(o => o.Price)

Sign up to request clarification or add additional context in comments.

Comments

3

The other option is to use the LINQ query syntax instead of the method syntax:

 List<Order> sortedOrders = from o in orders
 orderby o.Date, O.Price
 select o;

2 Comments

If I understand correctly - the use of two fields within 'orderby' separated by a comma results in a form of grouping if the o.Date has a bunch of records of the same Date value - ordering the records O.Price ascending within the matching Date. ?
Yes, that's right. Same as the accepted answer. Just using a different syntax.
1

You can use:

orders.OrderBy(o => o.Date).ThenBy(o => o.Price)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.