【问题标题】:Grouping a list of dictionaries in C#在 C# 中对字典列表进行分组
【发布时间】:2021-10-26 08:11:27
【问题描述】:

我有一个字典列表如下:

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}

【问题讨论】:

  • 我猜原始数据来自sql什么的?如果是这种情况,我建议将数据反序列化为对象而不是字典。
  • @LeisenChang 是的,如果将其反序列化为对象,编写linq查询将变得更加简单。但是我们的系统允许用户动态添加新字段而无需重新编译代码,所以字典类型是我找到的最好的方式(暂时)......

标签: c# list linq dictionary


【解决方案1】:

这应该可行:

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

【讨论】:

  • 字典结果加 1,虽然说实话不应该有字典涉及输入或输出 :) 似乎可能是上游有问题的设计决策
  • @TheGeneral:是的,通常你会使用类而不是字典;)
【解决方案2】:

给定

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

【讨论】:

  • 虽然结果不是字典格式,但这正是我想要的。谢谢!
  • @alexkor1911 nps,祝你好运
猜你喜欢
  • 1970-01-01
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-06
  • 1970-01-01
  • 2018-10-19
  • 2018-08-14
相关资源
最近更新 更多