使用linq对多个进行分组[重复]
Posted
技术标签:
【中文标题】使用linq对多个进行分组[重复]【英文标题】:Group BY multiple using linq [duplicate] 【发布时间】:2016-07-20 06:19:08 【问题描述】:尝试按多个文件分组,但遇到问题。我想按时间段、产品代码分组。
var ProductUsageSummary = from b in myProductUsage
group b by b.ProductCode into g
select new
Period = g.Key,
Code = g.Key,
Count = g.Count(),
TotalQty = g.Sum(n => n.Qty),
Price = g.Average(n => n.Price)
;
也试过
var ProductUsageSummary = from b in myProductUsage
group b by b.Period b.ProductCode into g
select new
Period = g.Key(n => n.period),
Code = g.Key,
Count = g.Count(),
TotalQty = g.Sum(n => n.Qty),
Price = g.Average(n => n.Price)
;
【问题讨论】:
【参考方案1】:您可以创建一个匿名对象来对多列进行分组(例如...new prop1 prop2
),Key.PropertyName
可以访问分组的字段
试试这个。
var ProductUsageSummary = from b in myProductUsage
group b by new b.Period, b.ProductCode into g
select new
Period= g.Key.Period,
Code = g.Key.ProductCode ,
Count = g.Count(),
TotalQty = g.Sum(n => n.Qty),
Price = g.Average(n => n.Price)
;
【讨论】:
【参考方案2】:这是使用匿名类型的正确语法:
group b by new b.ProductCode, b.Period into g
然后在选择中:
g.Key.ProductCode
和 g.Key.Period
完整查询:
var ProductUsageSummary = from b in myProductUsage
group b by new b.Period b.ProductCode into g
select new
Period = g.Key.Period,
Code = g.Key.ProductCode,
Count = g.Count(),
TotalQty = g.Sum(n => n.Qty),
Price = g.Average(n => n.Price)
;
【讨论】:
以上是关于使用linq对多个进行分组[重复]的主要内容,如果未能解决你的问题,请参考以下文章