score:59

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

score:-1

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

dataGridView1.DataSource = New1;

score:7

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));
}

score:16

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


Related Query

More Query from same tag