LINQ按多个字段分组-语法帮助


74

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

Answers:


137

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

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中。)


乔恩,我在使用扩展方法时总是犯错误,有什么简单的方法可以熟悉吗?
乌达纳2009年

@Udana:我发现查看C#编译器对查询表达式的作用非常有帮助-但我是一个基于规范的人。查看可用的重载并阅读文档也有很多帮助:)
Jon Skeet 2009年

@Jon Skeet:这种重载GroupBy()在MSDN中没有太多描述。你能写一行吗?
FMFF 2012年

4
@FMFF:(msmvps.com/blogs/jon_skeet/archive/2011/01/01/…)据我所知,这种重载groupBy(x=>x.y, (key,group)=>[lambda with group and key])只是一种较短的表达方式 GroupBy(x=>x.y).select(group=>[lambda with group and group.key]),第二种似乎更具可读性
HugoRune

4
我发现使用linqpad还能带来一些好处,因为您可以在linq中写一些东西之后从lambda和SQL之间切换:“从foo in bar中选择foo”语法
Jim Wolff
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.