Mega Code Archive

 
Categories / C# Book / 04 LINQ
 

0513 Average - Grouped

public void Linq91() { List<Product> products = GetProductList(); var categories = from p in products group p by p.Category into g select new { Category = g.Key, AveragePrice = g.Average(p => p.UnitPrice) }; ObjectDumper.Write(categories); } Result Category=Beverages Category=Condiments Category=Produce Category=Meat/Poultry Category=Seafood Category=Dairy Products Category=Confections Category=Grains/Cereals AveragePrice=37.979166666666666666666666667 AveragePrice=23.0625 AveragePrice=32.3700 AveragePrice=54.006666666666666666666666667 AveragePrice=20.6825 AveragePrice=28.7300 AveragePrice=25.1600 AveragePrice=20.2500