[英]Grouping a list of dictionaries in C#
I have a list of dictionaries as below:我有一个字典列表如下:
List<Dictionary<string, object>> itemList = new List<Dictionary<string, object>>();
itemList.Add(new Dictionary<string, object>() {
{ "Item", "001" },
{ "Category", "A" },
{ "Quantity", 5 }
});
itemList.Add(new Dictionary<string, object>() {
{ "Item", "002" },
{ "Category", "B" },
{ "Quantity", 8 }
});
itemList.Add(new Dictionary<string, object>() {
{ "Item", "001" },
{ "Category", "A" },
{ "Quantity", 6 }
});
How would I write my Linq query so that I can get the result as below我将如何编写我的 Linq 查询,以便获得如下结果
Output (list of dictionaries):
{ "Item" = "001", "Category" = "A", "Quantity" = 11},
{ "Item" = "002", "Category" = "B", "Quantity" = 8}
Given给定的
var results = itemList
.GroupBy(x => new { Item = x["Item"], Category = x["Category"] })
.Select(x => new
{
x.Key.Item,
x.Key.Category,
Quantity = x.Sum(y => (int)y["Quantity"])
});
foreach (var result in results)
Console.WriteLine($"{result.Item} {result.Category} {result.Quantity}");
Output输出
001 A 11
002 B 8
This should work:这应该有效:
List<Dictionary<string, object>> resultList = itemList
.Select(d => (Item:d["Item"], Category:d["Category"], Quantity:d["Quantity"]))
.GroupBy(x => (Item: x.Item, Category: x.Category))
.Select(g => new Dictionary<string, object> { {"Item",g.Key.Item},{"Category",g.Key.Category},{"Quantity",g.Sum(x => (int)x.Quantity)}})
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.