使用linq对BY倍数进行分组
本文关键字:linq BY 使用 | 更新日期: 2023-09-27 17:57:42
试图按多个文件进行分组,但遇到问题。我想按周期、产品代码进行分组。
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)
};
您可以创建一个匿名对象来对多列进行分组(例如…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)
};
这是使用匿名类型的正确语法:
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)
};