LINQ Group By Multiple fields -Syntax help

时间:2009-12-08 18:40:03

标签: c# linq group-by

为了按多列分组,示例2 需要进行哪些更正

示例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() };

示例2(不正确)

   var qry = 
   cust.GroupBy(p => p.Customer, q => q.OrderDate, (k1, k2, group) =>
   new { Key1 = k1, Key2 = k2, Count = group.Count() });

1 个答案:

答案 0 :(得分:134)

在查询表达式中使用点符号使用相同的匿名类型:

var qry = cust.GroupBy(cm => new { cm.Customer, cm.OrderDate }, 
             (key, group) => new { Key1 = key.Customer, Key2 = key.OrderDate, 
                                   Count = group.Count() });

(在一个真正的IDE中,我(key, group)cm参数下排成一行,但它会包含在SO中。)