我有一個字典串列如下:
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 }
});
我將如何撰寫我的 Linq 查詢,以便獲得如下結果
Output (list of dictionaries):
{ "Item" = "001", "Category" = "A", "Quantity" = 11},
{ "Item" = "002", "Category" = "B", "Quantity" = 8}
uj5u.com熱心網友回復:
給定的
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}");
輸出
001 A 11
002 B 8
uj5u.com熱心網友回復:
這應該有效:
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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340920.html
上一篇:C#使用組選擇重復項
下一篇:使用子查詢將SQL轉換為LINQ
