2008-12-12 63 views
33

我在Framework 3.5上使用C#。我期望通過兩個屬性快速將通用列表<>分組。爲了這個例子,可以說我有一個訂單類型的列表,具有CustomerId,ProductId和ProductCount屬性。我如何使用lambda表達式獲得由CustomerId和ProductId分組的ProductCounts的總和?C#List <> GroupBy 2 Values

回答

56
var sums = Orders.GroupBy(x => new { x.CustomerID, x.ProductID }) 
       .Select(group => group.Sum(x => x.ProductCount)); 
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)); 
} 
16

我知道這個線程是很老,但因爲我只是通過這個語法掙扎,我想我」 ð發佈我的新結論 - 你可以在一個查詢(/ W 0的foreach)返回之和的ID,像這樣:

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

最棘手的部分,我得到它的工作是和必須的別名,顯然...

+0

我意識到這個答案很古老,但如果有人想知道爲什麼別名是必要的,屬性會生成隱式字段名稱,但方法不會。 – Jimmy 2012-11-20 23:26:39

-1

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

dataGridView1.DataSource = New1;

+0

此答案似乎不適用於該問題。 – Bryan 2013-07-14 13:52:41

相關問題