C# 获取嵌套字典的嵌套值的总和

C# Getting the sum of nested values of a nested dictionary

我有一个具有以下结构的字典:

{
    "group_1": {
        "a": 1.0,
        "b": 1.5,
        "c": 2.0,
        "d": 4.0
    },
    "group_2": {
        "a": 3.0,
        "b": 3.5,
        "c": 6.0,
        "d": 4.7
    },
    "group_3": {
        "a": 0,
        "b": 1.9,
        "c": 2.1,
        "d": 3.0
    },
    "group_4": {
        "a": 0.4,
        "b": 1.3,
        "c": 1.0,
        "d": 2.0
    }
}

我想做的是将所有兄弟字典的所有对应值相加并创建一个新字典,如下所示:

{
    "a": 3.4,
    "b": 7.2,
    "c": 11.1,
    "d": 13.7
}

我想用一种更简洁优雅的方式,它需要是动态的,因为我不能确定有多少组词典或有多少字母。

我已经尝试过 foreach 方法,但我真的不明白如何在每个循环中只获取每个字典的位置值。

var formatedDataList = new Dictionary<string, decimal>();
foreach (KeyValuePair<string, Dictionary<string, string>> group in fortmatedData)
{
    foreach (KeyValuePair<string, string> alternative in group.Value)
    {
        ...
    }
}

谁能帮帮我?

只需遍历内部字典并添加一个键(如果不存在):

dict.Aggregate(new Dictionary<string, double>(), (x, y) => {
    foreach (var kvp in y.Value) {
        x[kvp.Key] = (x.TryGetValue(kvp.Key, out var sum) ? sum : 0) + kvp.Value;
    }
    return x;
});

此解决方案的复杂度比分组解决方案小 3 倍。可用于更大的数据集。

您可以使用 LINQ:

var formatedDataList = fortmatedData
    .SelectMany(kvp => kvp.Value) // Flatten nested dictionaries
    .GroupBy(kvp => kvp.Key)
    .ToDictionary(grp => grp.Key, grp => grp.Sum(kvp => kvp.Value));