如何编写一个LINQ查询结合group by和aggregate?

时间:2011-05-05 23:52:32

标签: c# .net linq

根据以下输入,如何编写LINQ查询或表达式以返回数量的聚合结果集?

输入:

var foo = new[] { new { PO = "1", Line = 2, QTY = 0.5000 }, 
                  new { PO = "1", Line = 2, QTY = 0.2500 }, 
                  new { PO = "1", Line = 2, QTY = 0.1000 }, 
                  new { PO = "1", Line = 2, QTY = -0.1000 } 
                }.ToList();

期望的结果:

的内容
new { PO = "1", Line = 2, QTY = 0.7500 } // .5 + .25 + .1 + -.1

我如何为多行编写它(参见foo中的对象模型)?

2 个答案:

答案 0 :(得分:5)

这个怎么样:

var result = foo.GroupBy(x => x.Line)
                .Select(g => new { PO = g.First().PO, 
                                   Line = g.Key, 
                                   QTY = g.Sum(x => x.QTY) });

如果您只有一行,只需添加.Single() - result是设置IEnumerable时定义的匿名类型的foo

修改

如果PO和Line都应指定不同的组(PO可以具有不同的值),则它们都必须是组密钥的一部分:

var result = foo.GroupBy(x => new { x.PO, x.Line})
                .Select(g => new { 
                    PO = g.Key.PO, 
                    Line = g.Key.Line, 
                    QTY = g.Sum(x => x.QTY) 
                  });

答案 1 :(得分:1)

var query = (from t in foo
                         group t by new {t.PO, t.Line}
                         into grp
                             select new
                                        {
                                            grp.Key.PO,
                                            grp.Key.Line,
                                            QTY = grp.Sum(t => t.QTY)
                                        }).ToList()