LINQ Group By Multiple fields -Syntax help
What is the correction needed for example 2 inorder to group by multiple columns
Example 1
var query = from cm in cust
group cm by new { cm.Customer, cm.OrderDate } into cms
select
new
{ Key1 = cms.Key.Customer,Key2=cms.Key.OrderDate,Count=cms.Count() };
Example 2 (incorrect)
var qry =
cust.GroupBy(p => p.Customer, q => q.OrderDate, (k1, k2, group) =>
new { Key1 = k1, Key2 = k2, Count = group.Count() });
Solution 1:
Use the same anonymous type in the dot notation that you do in the query expression:
var qry = cust.GroupBy(cm => new { cm.Customer, cm.OrderDate },
(key, group) => new { Key1 = key.Customer, Key2 = key.OrderDate,
Count = group.Count() });
(In a real IDE I'd have (key, group)
lined up under the cm
parameter, but then it would wrap in SO.)