C#List <> GroupBy 2值

Saa*_*per 34 c# linq ienumerable group-by list

我在Framework 3.5上使用C#.我希望通过两个属性快速对Generic List <>进行分组.为了这个例子,我假设我有一个Order类型的List,其中包含CustomerId,ProductId和ProductCount属性.如何使用lambda表达式获取CustomerId和ProductId分组的ProductCounts总和?

Jim*_*mmy 57

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


Tod*_*don 16

我意识到这个线程已经很老了但是因为我只是努力通过这个语法我想我会发布我的其他发现 - 你可以在一个查询中返回总和和ID(没有foreach),如下所示:

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

让我工作的棘手部分是总和必须是别名,显然......


Kla*_*urn 7

或者,如果您想获得每笔金额的ID,您可以这样做

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));
}
Run Code Online (Sandbox Code Playgroud)