C# LINQ Group By Multiple fields - 语法帮助

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1869001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:30:40  来源:igfitidea点击:

LINQ Group By Multiple fields -Syntax help

c#linqgroup-by

提问by Udana

What is the correction needed for example 2inorder to group by multiple columns

例如 2需要什么更正才能按多列分组

Example 1

示例 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)

例2(错误)

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

采纳答案by Jon Skeet

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 cmparameter, but then it would wrap in SO.)

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