使用 Linq 进行多重分组
使用 Linq 进行多重分组
这个问题已经有了答案:
尝试按多个字段进行分组,但遇到问题。我想按期间和产品代码进行分组。
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) };
admin 更改状态以发布 2023年5月21日
这是使用匿名类型的正确语法:
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) };
你可以创建一个匿名对象来按多列进行分组(例如... 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) };