C# List<> GroupBy 2 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/363655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# List<> GroupBy 2 Values
提问by SaaS Developer
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?
我在 Framework 3.5 上使用 C#。我希望通过两个属性快速将 Generic List<> 分组。就本示例而言,假设我有一个 Order 类型的 List,其中包含 CustomerId、ProductId 和 ProductCount 的属性。如何使用 lambda 表达式获得按 CustomerId 和 ProductId 分组的 ProductCounts 的总和?
采纳答案by Jimmy
var sums = Orders.GroupBy(x => new { x.CustomerID, x.ProductID })
.Select(group => group.Sum(x => x.ProductCount));
回答by Klas Mellbourn
Alternatively, if you want to get the IDs for each sum, you could do this
或者,如果您想获取每个总和的 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));
}
回答by Todd Langdon
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:
我意识到这个线程很老了,但由于我只是在这个语法中挣扎,我想我会发布我的其他发现 - 您可以在一个查询中返回总和和 ID(不带 foreach),如下所示:
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...
我让它工作的棘手部分是总和必须是别名,显然......
回答by AnshuMan SrivAstav
var New1 = EmpList.GroupBy(z => z.Age).OrderBy(Employee => Employee.Key);
var New1 = EmpList.GroupBy(z => z.Age).OrderBy(Employee => Employee.Key);
dataGridView1.DataSource = New1;
dataGridView1.DataSource = New1;