Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# List<> GroupBy 2 Values

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?

like image 545
SaaS Developer Avatar asked Dec 12 '08 18:12

SaaS Developer


2 Answers

var sums = Orders.GroupBy(x => new { x.CustomerID, x.ProductID })                  .Select(group => group.Sum(x => x.ProductCount)); 
like image 165
Jimmy Avatar answered Oct 06 '22 14:10

Jimmy


I realize this thread is very old but since I just struggled through this syntax I thought I'd post my additional findings - you can return the sum and the IDs (w/o foreach) in one query like so:

var sums = Orders             .GroupBy(x => new { x.CustomerID, x.ProductID })             .Select(group =>new {group.Key, ProductCount = group.Sum(x => x.ProductCount)}); 

The tricky part for me to get it working is that the sum must be aliased, apparently...

like image 33
Todd Langdon Avatar answered Oct 06 '22 13:10

Todd Langdon