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);
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);
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.
If you use SelectMany()
, you flatten this List inside a List into one List
var Result = lstOrderItems.GroupBy(p=> p.CatID).Select(group => group.OrderByDescending(d=> d.itemPrice));