使用linq分组BY多个

时间:2016-07-20 06:19:09

标签: c# 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)
                            };

2 个答案:

答案 0 :(得分:2)

您可以创建一个匿名对象,以便对多个列进行分组(例如... 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)
                          };

答案 1 :(得分:0)

这是使用匿名类型的正确语法:

group b by new { b.ProductCode, b.Period } into g

然后在选择:

g.Key.ProductCodeg.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)
                          };