可能重复:
在C#中合并字典
字典1
"a","1"
"b","2"
字典2
"c","3"
"d","4"
字典3
"e","5"
"f","6"
组合字典
"a","1"
"b","2"
"c","3"
"d","4"
"e","5"
"f","6"
如何将上述3个词典合并为一个组合词典?
考虑下面的代码,这是一个合并到一个字典的字典列表,这可以用 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;
}
Run Code Online (Sandbox Code Playgroud)