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

Community
  • 1
  • 1
Shane
  • 296
  • 2
  • 6
  • 2
    its weird how many of this exact same question I've seen today. – Phillip Schmidt Aug 03 '12 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](http://stackoverflow.com/questions/298725/multiple-order-by-in-linq) post. – Nathan Aug 03 '12 at 15:25
  • 2
    actually, its a duplicate of [this](http://stackoverflow.com/questions/298725/multiple-order-by-in-linq), [this](http://stackoverflow.com/questions/2318885/multiple-order-by-with-linq), [this](http://stackoverflow.com/questions/4613602/how-to-apply-multiple-orderby-in-linq-query), [this](http://stackoverflow.com/questions/958220/how-can-i-use-linq-to-sort-by-multiple-fields),[this](http://stackoverflow.com/questions/6270374/linq-multiple-order-by),[this](http://stackoverflow.com/questions/3084671/linq-multiple-order-by), etc – Phillip Schmidt Aug 03 '12 at 15:27
  • Sorry, I'm new to this site... tried to find it but I missed it. Thanks. – Shane Aug 03 '12 at 16:47

3 Answers3

35

You want to use the ThenBy function:

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

FAtBalloon
  • 4,500
  • 1
  • 25
  • 33
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;
scott.korin
  • 2,537
  • 2
  • 23
  • 36
  • 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. ? – Martin Sansone - MiOEE Mar 03 '14 at 21:32
  • Yes, that's right. Same as the accepted answer. Just using a different syntax. – scott.korin Mar 05 '14 at 15:39
1

You can use:

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

Am1rr3zA
  • 7,115
  • 18
  • 83
  • 125