Mega Code Archive

 
Categories / C# Book / 04 LINQ
 

0470 GroupBy - Nested

public void Linq43() { List<Customer> customers = GetCustomerList(); var customerOrderGroups = from c in customers select new { c.CompanyName, YearGroups = from o in c.Orders group o by o.OrderDate.Year into yg select new { Year = yg.Key, MonthGroups = from o in yg group o by o.OrderDate.Month into mg select new { Month = mg.Key, Orders = mg } } }; ObjectDumper.Write(customerOrderGroups, 3); } Result CompanyName=Alfreds Futterkiste YearGroups=... YearGroups: Year=1997 MonthGroups=... MonthGroups: Month=8 Orders=... Orders: OrderID=10643 OrderDate=8/25/1997 Total=814.50 MonthGroups: Month=10 Orders=... Orders: OrderID=10692 OrderDate=10/3/1997 Total=878.00 Orders: OrderID=10702 OrderDate=10/13/1997 Total=330.00 YearGroups: Year=1998 MonthGroups=... MonthGroups: Month=1 Orders=... Orders: OrderID=10835 OrderDate=1/15/1998 Total=845.80 MonthGroups: Month=3 Orders=... Orders: OrderID=10952 OrderDate=3/16/1998 Total=471.20 MonthGroups: Month=4 Orders=...