0

I am doing it this way but it won't work (Do not compile), i need to GroupBy first then OrderBy.

lstOrderItems.OrderBy(x => x.itemPrice).GroupBy(p => p.CatID);
NoviceToDotNet
  • 9,889
  • 32
  • 106
  • 163
  • 3
    Can you specify expected result? Question is not clear - what should be output - sorted groups or items, should you take first ten, or not? Very vague for person with almost 2K rep – Sergey Berezovskiy Mar 20 '14 at 08:20
  • Remove "It doesn't work" from your vocabulary. That's not helpful. It does not tell anybody anything. You need to be precise for people to be able to help you. – nvoigt Mar 20 '14 at 08:25
  • What is this? Linq-To-Entities? Linq-to-Objects? – Marco Mar 20 '14 at 08:27
  • linq to object..i have collection of lstOrderItems that each hold orderItem object. – NoviceToDotNet Mar 20 '14 at 08:29
  • possible duplicate of [linq group by, order by](http://stackoverflow.com/questions/9132964/linq-group-by-order-by) – SuicideSheep Mar 20 '14 at 08:30

2 Answers2

4
var Result = lstOrderItems.GroupBy(p=> p.CatID).Select(group => group.OrderByDescending(d=> d.itemPrice));
Sajeetharan
  • 203,447
  • 57
  • 330
  • 376
  • If i take this data in result and make any changes on result will it make changes to the lstOrderItems as well? – NoviceToDotNet Mar 20 '14 at 08:32
  • 1
    No, it wont make changes to lstOrderItems, you have to use the resulted list for further process, what you can do is assign the resulting list to Collection of the same type! – Sajeetharan Mar 20 '14 at 08:33
4

You have a problem of understanding here. If you do a grouping you'll have a property to work with: the key.

I am taking the northwind database with the products table here as reference. If you Group products by CategoryId Products.GroupBy (p => p.CategoryID) you can then append OrderBy of course. But the only property you can order by afterwards is the key:

//p.Key is the CategoryId after which you grouped by
Products.GroupBy (p => p.CategoryID).OrderBy (p => p.Key)

What you need to do is, is select the grouping and work with it:

Products.GroupBy (p => p.CategoryID).Select (p => p.OrderBy (x => x.UnitPrice))

If you want to flatten your result use SelectMany:

Products.GroupBy (p => p.CategoryID).SelectMany (p => p.OrderBy (x => x.UnitPrice))

EDIT To clarify the Select/SelectMany issue: This is what you'll get using Select. A return type of IOrderedQueryable<IOrderedEnumberable<Products>>. In essence a List inside a List.

enter image description here

If you use SelectMany(), you flatten this List inside a List into one List

enter image description here

Marco
  • 20,296
  • 6
  • 68
  • 109