Home > Mobile >  Grouping a list of dictionaries in C#
Grouping a list of dictionaries in C#

Time:10-26

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}

CodePudding user response:

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

CodePudding user response:

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