简体   繁体   中英

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 = 2, 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM