Tuesday, May 24, 2011

LINQ Group By And Sum

Problem: LINQ syntax for grouping a set of records together and performing a sum of some of the values.

Solution: This example shows a group clause that uses multiple columns:

var query = from order in db.Orders
group order by new { Customer = order.Customer,
SalesPerson = order.SalesPerson }
into grp
select new
{
Customer = grp.Key.Customer.Name,
SalesPerson = grp.Key.SalesPerson.Name,
Quantity = grp.Sum(o => o.Quantity),
Amount = grp.Sum(o => o.Amount)
};

A simpler version is found here: http://msdn.microsoft.com/en-us/vcsharp/aa336747#sumGrouped e.g.

var categories =
from p in products
group p by p.Category into g
select new { Category = g.Key, TotalUnitsInStock = g.Sum(p => p.UnitsInStock) };

No comments:

Post a Comment