简体   繁体   中英

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM