1

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
  • 10,387
  • 36
  • 112
  • 166
  • 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

5

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
  • 22,856
  • 9
  • 75
  • 124
  • Could you explain the second one that SelectMany that flatten the results. – NoviceToDotNet Mar 20 '14 at 08:54
  • I'll give you 2 screenshots from Linqpad in a few minutes which will explain it to you. Otherwise: http://stackoverflow.com/questions/958949/difference-between-select-and-selectmany – Marco Mar 20 '14 at 08:56
4
var Result = lstOrderItems.GroupBy(p=> p.CatID).Select(group => group.OrderByDescending(d=> d.itemPrice));
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • 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