Sum - Grouped

Query
public void Linq80()
{
List products = GetProductList();

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

ObjectDumper.Write(categories);
}
Lambda Expression
public void Linq80()
{
List products = GetProductList();

var categories = products.GroupBy(prod => prod.Category).
Select(prodGroup => new {Category = prodGroup.Key, TotalUnitsInStock = prodGroup.Sum(p => p.UnitsInStock)});

ObjectDumper.Write(categories);
}
Output
Category=Beverages TotalUnitsInStock=559
Category=Condiments TotalUnitsInStock=507
Category=Produce TotalUnitsInStock=100
Category=Meat/Poultry TotalUnitsInStock=165
Category=Seafood TotalUnitsInStock=701
Category=Dairy Products TotalUnitsInStock=393
Category=Confections TotalUnitsInStock=386
Category=Grains/Cereals TotalUnitsInStock=308
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +