user3783297
user3783297

Reputation: 33

Group and sub group with linq

I have a class T with members ProductId, CategoryId, CategoryName and DateLastModified. What I'd like to achieve is to create a new list of an anonymous type (just going to loop through it in my view) that firstly groups on CategoryName then groups the CategoryNames by DateLastModified.Year & DateLastModified.Month

So far I have

var groupedList = list.GroupBy(x => new { x.CategoryName });

Where list is my List<T>

This groups by categoryName as key with the elements, just not sure on the next step

Thanks in advance

Upvotes: 0

Views: 335

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21825

You have to use Nested Group in that case, Try this:-

 var query = from pro in products
                       group pro by pro.CategoryName into newGroup1
                       from newGroup2 in
                           (from prod in newGroup1
                            group prod by new { prod.DateLastModified.Year, prod.DateLastModified.Month } 
                           )
                       group newGroup2 by newGroup1.Key;

Working Fiddle.

Upvotes: 3

Related Questions