C#Linq合并字典列表

时间:2019-09-11 21:32:49

标签: c# linq

考虑下面的代码,这是合并到一个Dictionary的Dictionary的列表,可以用linq编写吗?

    public static Dictionary<string, uint> mergeDictionaries(List<Dictionary<string, uint>> dictlist)
    {
        Dictionary<string, uint> mergedDict = new Dictionary<string, uint>();
        foreach (Dictionary<string, uint> dict in dictlist)
        {
            foreach (KeyValuePair<string, uint> entry in dict)
            {
                if (mergedDict.ContainsKey(entry.Key))
                {
                    mergedDict[entry.Key] = mergedDict[entry.Key] + entry.Value;
                }
                else
                {
                    mergedDict[entry.Key] = entry.Value;
                }
            }
        }
        return mergedDict;
    }

1 个答案:

答案 0 :(得分:3)

dictlist
    .SelectMany(dict => dict)
    .GroupBy(kvp => kvp.Key)
    .ToDictionary(g => g.Key, g => g.Sum(kvp => kvp.Value))