我在Framework 3.5上使用C#。我想快速分组通用列表<>由两个属性。为了这个例子,我假设我有一个Order类型的List,其中包含CustomerId,ProductId和ProductCount属性。如何使用lambda表达式获取CustomerId和ProductId分组的ProductCounts总和?
答案 0 :(得分:56)
var sums = Orders.GroupBy(x => new { x.CustomerID, x.ProductID })
.Select(group => group.Sum(x => x.ProductCount));
答案 1 :(得分:16)
我意识到这个帖子已经很老了但是因为我只是努力通过这个语法我想我会发布我的其他发现 - 你可以在一个查询中返回总和和ID(没有foreach),如下所示:
var sums = Orders
.GroupBy(x => new { x.CustomerID, x.ProductID })
.Select(group =>new {group.Key, ProductCount = group.Sum(x => x.ProductCount)});
让我工作的棘手部分是总和必须是别名,显然......
答案 2 :(得分: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));
}
答案 3 :(得分:-1)
var New1 = EmpList.GroupBy(z => z.Age).OrderBy(Employee => Employee.Key);
dataGridView1.DataSource = New1;