开发者

How to write a LINQ query combining group by and aggregates?

Given the following input, how do I write a LINQ query or expression to return an aggregated result set for the quantity?

Input:

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();

Desired result:

Something along the lines of

new { PO = "1", Line = 开发者_StackOverflow2, QTY = 0.7500 } // .5 + .25 + .1 + -.1

How would I write it for multiple lines as well (see the object model in foo)?


How about this:

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

In the case you just have one Line, just add a .Single() - result is an IEnumerable of the anonymous type defined when you set up foo.

Edit:

If both PO and Line should designate different groups (PO can have different values), they both have to be part of the group key:

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) 
                  });


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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜