【问题标题】:Sum values in double nested List of Dictionaries in C#C# 中双嵌套字典列表中的总和值
【发布时间】:2023-04-02 05:02:01
【问题描述】:

我有(由于某些原因现在不进入......)以下结构的列表:

List1<Dictionary1<string, List2<Dictionary2<string, string>>>>

(为了清楚起见,我添加了 1 和 2 的命名)。 我想遍历List1并总结Dictionary1,这样Dictionary2中相同键的所有值都会相加。

例如,如果每个 Dictionary1 项目包含一个 Dictionary2: { "价格", 23}, { "客户", 3}

然后我想遍历所有 List2 元素和所有 List1 元素,并将所有价格和客户总和的最终字典作为每个类别的单个键: {“价格”,15235}, {“客户”,236}

我希望这很清楚.. 换句话说,我想总结这个双重嵌套列表,让我留下所有嵌套字典中的所有唯一键,并对值进行总结。

我相信它可以用 LINQ 完成,但我不知道该怎么做..

【问题讨论】:

  • 为什么是第二种类型的“Dictionary2”字符串,而不是double或其他数字类型?
  • Dictionary1 的意义何在?如果我没看错的话,我看不到那个键被使用了吗?
  • 你需要一些更好的样本数据,和你预期的结果,这有点混乱
  • 子列表的深度是多少,2?
  • 仅供参考,“(为了清楚起见,我添加了 1 和 2 命名)” 在类型名称的末尾添加数字并不能说明问题,实际上恰恰相反。相反,发布可编译的代码可能是确保清晰的最佳方式:var data = new List&lt;Dictionary&lt;string, List&lt;Dictionary&lt;string, int&gt;&gt;&gt;&gt;();。请添加一个实际填充列表中某些项目的代码片段,然后说明预期结果应该是什么。

标签: c# list linq dictionary nested


【解决方案1】:

这可能是我写过的最丑陋的东西,并对你正在做的事情做了一些假设,但我认为这会让你得到你想要的:

var query = from outerDictionary in x
            from listOfDictionaries in outerDictionary.Values
            from innerDictionary in listOfDictionaries
            from keyValuePairs in innerDictionary
            group keyValuePairs by keyValuePairs.Key into finalGroup
            select new
            {
                Key = finalGroup.Key,
                Sum = finalGroup.Sum(a => Convert.ToInt32(a.Value))
            };

x 是你的主列表。

【讨论】:

    【解决方案2】:

    好的,看起来您正在尝试创建具有各种属性(成本、客户等)的项目字典,这就引出了一个问题:为什么不只创建一个类?

    毕竟,将项目字典转换为单个属性字典非常简单,如下所示。

    public class ItemProperties 
    {
    public double Price {get; set;} = 0;
    public int Customers {get; set;} = 0;
    //Whichever other properties you were thinking of using. 
    }
    
    static ItemProperties AddAll(Dictionary<string, ItemProperties> items)
    ItemProperties finalitem = new ItemProperties(); 
    {
    foreach (var item in items) 
    {
    finalitem.Price += item.Price;
    finalitem.Customers += item.Customers;
    //Repeat for all other existing properties.
    }
    return finalitem;
    }
    

    当然,这仅适用于属性的数量和种类不可变的情况。解决此问题的另一种方法是使用 TryParse 在 Dictionary2 中查找您认为可以添加的属性。然而,这是有问题的,并且需要一些良好的错误检查。

    static Dictionary < string, string > AddNestedDictionary(Dictionary < string, Dictionary < string, string > items) {
    
     Dictionary < string, string > finalitem = new Dictionary < string, string > ();
     foreach(var item in items) {
      foreach(var prop in item) {
       if (!finalitem.ContainsKey(prop.Key)) {
        finalitem.Add(prop);
       }
       double i = 0;
       if (Double.TryParse(prop.Value, out i)) {
        finalitem[prop.Key] += i;
       }
      }
     }
    return finalitem;
    }
    

    同样,与静态类的简单性相比,这不是最佳答案。但这将是您为不清晰所付出的代价。

    【讨论】:

      猜你喜欢
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 2022-01-21
      • 2017-06-17
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多