SaaS Developer
SaaS Developer

Reputation: 9895

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?

Upvotes: 37

Views: 72700

Answers (4)

AnshuMan SrivAstav
AnshuMan SrivAstav

Reputation: 67

var New1 = EmpList.GroupBy(z => z.Age).OrderBy(Employee => Employee.Key);

dataGridView1.DataSource = New1;

Upvotes: -1

Jimmy
Jimmy

Reputation: 91492

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

Upvotes: 63

Todd Langdon
Todd Langdon

Reputation: 385

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...

Upvotes: 17

Klas Mellbourn
Klas Mellbourn

Reputation: 44407

Alternatively, if you want to get the IDs for each sum, you could do this

var customerAndProductGroups =
    from order in Orders
    orderby order.CustomerID, order.ProductID // orderby not necessary, but neater
    group order by new { order.CustomerID, order.ProductID };

foreach (var customerAndProductGroup in customerAndProductGroups)
{
    Console.WriteLine("Customer {0} has ordered product {1} for a total count of {2}",
        customerAndProductGroup.Key.CustomerID,
        customerAndProductGroup.Key.ProductID,
        customerAndProductGroup.Sum(item => item.ProductCount));
}

Upvotes: 7

Related Questions