【问题标题】:How to Multiply and sum nested dictionary in C#?如何在 C# 中对嵌套字典进行乘法和求和?
【发布时间】:2018-04-27 06:49:30
【问题描述】:

我有一个具有这种结构的 C# 字典:

Dictionary<int, Dictionary<string, double>> dictionary = new Dictionary<int, Dictionary<string, double>>
        {
            {
                0, new Dictionary<string, double>
                {
                    { "eat",0.15 },
                    { "food", 0.16 }
                }
            },
            {
                1, new Dictionary<string, double>
                {
                    { "eat",0.32 },
                    { "food", 0.2 }
                }
            },
        };

我想在其他字典中求和和相乘,

0.15 * 0.32 + 0.16 * 0.2

我应该怎么做才能用 foreach 在 c# 中编写代码?

谢谢

【问题讨论】:

    标签: c# dictionary nested


    【解决方案1】:

    这是一个 LINQ 解决方案:

    Dictionary<int, Dictionary<string, double>> dict = new Dictionary<int, Dictionary<string, double>>() {
        {0,new Dictionary<string, double> { { "eat",0.15 }, { "food", 0.16 } } },
        {1,new Dictionary<string, double> { { "eat",0.32 }, { "food", 0.2 } } }
    };
    
    double eat = dict.Values.Select(x => x["eat"]).Aggregate((x, y) => x * y);
    double food = dict.Values.Select(x => x["food"]).Aggregate((x, y) => x * y);
    
    double result = eat + food;
    

    编辑

    这是一个更紧凑和通用的解决方案:

    var result = dict.SelectMany(x => x.Value)
                     .GroupBy(x => x.Key, y => y.Value, (Key, Value) => new { Value })
                     .Sum(x => x.Value.Aggregate((a, b) => a * b));
    

    结果 = 0.08

    DEMO HERE

    【讨论】:

    • 如果你分组和求和,你可以在 1 行中得到这个
    • @TheGeneral 我只是在尝试,但如果您有解决方案,您可以发布您的解决方案
    • @TheGeneral 我刚刚发布了一个新的灵魂,你能看看吗
    【解决方案2】:

    你可以这样做

    var dict = new Dictionary<int, Dictionary<string, double>>() {
                      {0, new Dictionary<string, double>() {{"eat", 0.15}, {"food", 0.16}}}, 
                      {1, new Dictionary<string, double>() {{"eat", 0.32}, {"food", 0.2}}}};
    
    var total = dict.Values.SelectMany(x => x)                // Flatten
                    .GroupBy(x => x.Key)                      // Group by key
                    .Sum(x => x.Select(y => y.Value)          // sum list of sub values
                               .Aggregate((y, z) => y * z));  // multiply
    
    Console.WriteLine(total);
    

    输出

    0.08
    

    Full Demo here

    【讨论】:

    • 你的解决方案比我的要优雅一点,所以我会投票 +1
    【解决方案3】:

    您可以使用 foreach 循环和最后的一些 linq 来解决此问题,如下所示:

    Dictionary<int, Dictionary<string, double>> data = new Dictionary<int, Dictionary<string, double>>()
            {
                {
                    0,new Dictionary<string, double>(){{ "eat" , 0.15 },{ "food" , 0.16} }
                },
                {
                    1,new Dictionary<string, double>(){{ "eat" , 0.32 },{ "food" , 0.2 } }
                }
            };
            Dictionary<string, double> finalResultDic = new Dictionary<string, double>();
            foreach (var entry in data)
            {
                foreach (var subEntry in entry.Value)
                {
                    if (finalResultDic.ContainsKey(subEntry.Key))
                    {
                        finalResultDic[subEntry.Key] *= subEntry.Value;
                    }
                    else
                    {
                        finalResultDic.Add(subEntry.Key, subEntry.Value);
                    }
                }
            }
            var finalResult = finalResultDic.Sum(dic => dic.Value);
    

    【讨论】:

      【解决方案4】:

      尝试以下:

                  Dictionary<int, Dictionary<string, double>> dict = new Dictionary<int,Dictionary<string,double>>() {
                     {0, new Dictionary<string,double>() {{"eat" , 0.15}, {"food" , 0.16}}}, 
                     {1, new Dictionary<string,double>(){{"eat", 0.32},{"food", 0.2}}}
                  };
      
                  double total = dict.Select(x => x.Value.Select(y => x.Key * y.Value).Sum()).Sum();
      

      【讨论】:

      • 结果错误,你得到的是0.52而不是0.08
      猜你喜欢
      • 2016-09-17
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 2016-01-17
      • 2018-11-23
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多