C# List<> GroupBy 2 Values

SaaS Developer picture SaaS Developer · Dec 12, 2008 · Viewed 66.1k times · Source

I'm using C# on Framework 3.5. I'm looking to quickly group a Generic List<> by two properties. For the sake of this example lets say I have a List of an Order type with properties of CustomerId, ProductId, and ProductCount. How would I get the sum of ProductCounts grouped by CustomerId and ProductId using a lambda expression?

Answer

Jimmy picture Jimmy · Dec 12, 2008
var sums = Orders.GroupBy(x => new { x.CustomerID, x.ProductID })
                 .Select(group => group.Sum(x => x.ProductCount));