我在Framework 3.5上使用C#。我期望通過兩個屬性快速將通用列表<>分組。爲了這個例子,可以說我有一個訂單類型的列表,具有CustomerId,ProductId和ProductCount屬性。我如何使用lambda表達式獲得由CustomerId和ProductId分組的ProductCounts的總和?C#List <> GroupBy 2 Values
33
A
回答
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)});
最棘手的部分,我得到它的工作是和必須的別名,顯然...
-1
var New1 = EmpList.GroupBy(z => z.Age).OrderBy(Employee => Employee.Key);
dataGridView1.DataSource = New1;
+0
此答案似乎不適用於該問題。 – Bryan 2013-07-14 13:52:41
相關問題
- 1. Casting C#List <>
- 2. C#List <string>「contains」question
- 3. List <dynamic>().Add problem C#
- 4. 哪個.NET集合更快:枚舉foreach Dictionary <>。Values或List <>?
- 5. Drools .NET 3.0 - List <> C#
- 6. c#List <Class> Additions
- 7. C#List <dictionary> To Json
- 8. List <> .Tag值在C#
- 9. C#:Abstract List <string>
- 10. C#List <string> [] to Datatable
- 11. STL multimap與.NET Dictionary <key,List <values>>有什麼不同?
- 12. Linq |在一個List <>
- 13. List <Map <String,List <>>> in BaseAdapter,Android
- 14. Vector <Customer> C++,List <Customer>&Vector <Customer> Java
- 15. LINQ的GroupBy列表<>
- 16. IDictionary <String,List <OpenXmlCompositeElement >> - 獲取List <OpenXmlCompositeElement>?
- 17. List <Map <String,String >> vs List <Object>
- 18. 如何將List <Class>轉換成C#中的Dictionary <string,List <String>>?
- 19. 比較2的List <詞典<字符串,對象>>在C#
- 20. List vs List <Object>?
- 21. C#從Dictionary獲取值<string,List <object>>
- 22. C#List <> - 插入數據庫
- 23. 如何實現從List <SomeParamType>到List的轉換<SomeParamType <?>>
- 24. List <string> binding
- 25. 如何轉換List <KeyValuePair <string,decimal >> list = new List <KeyValuePair <string,decimal >>();到DataTable?
- 26. c#List <string>作業問題
- 27. C#List <> Add()方法的性能
- 28. jQuery select values as list
- 29. JAXB - List <Serializable>?
- 30. List <> OrderBy IComparer?
我意識到這個答案很古老,但如果有人想知道爲什麼別名是必要的,屬性會生成隱式字段名稱,但方法不會。 – Jimmy 2012-11-20 23:26:39