C# 将多个字典合并为一个字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10559367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Combine multiple dictionaries into a single dictionary
提问by dotnet-practitioner
Possible Duplicate:
Merging dictionaries in C#
可能的重复:
在 C# 中合并字典
dictionary 1
字典 1
"a", "1"
"b", "2"
"a", "1"
"b", "2"
dictionary 2
字典2
"c", "3"
"d", "4"
"c", "3"
"d", "4"
dictionary 3
字典3
"e", "5"
"f", "6"
"e", "5"
"f", "6"
Combined dictionary
组合字典
"a", "1"
"b", "2"
"c", "3"
"d", "4"
"e", "5"
"f", "6"
"a", "1"
"b", "2"
"c", "3"
"d", "4"
"e", "5"
"f", "6"
How do I combine the above 3 dictionaries into a single combined dictionary?
如何将上述 3 个字典组合成一个组合字典?
采纳答案by Magnus
var d1 = new Dictionary<string, int>();
var d2 = new Dictionary<string, int>();
var d3 = new Dictionary<string, int>();
var result = d1.Union(d2).Union(d3).ToDictionary (k => k.Key, v => v.Value);
EDIT
To ensure no duplicate keys use:
编辑
为了确保没有重复的键使用:
var result = d1.Concat(d2).Concat(d3).GroupBy(d => d.Key)
.ToDictionary (d => d.Key, d => d.First().Value);
回答by Ry-
Just loop through them:
只需循环遍历它们:
var result = new Dictionary<string, string>();
foreach (var dict in dictionariesToCombine) {
foreach (var item in dict) {
result.Add(item.Key, item.Value);
}
}
(Assumes dictionariesToCombineis some IEnumerableof your dictionaries to combine, say, an array.)
(假设dictionariesToCombine是IEnumerable您的一些字典来组合,比如说,一个数组。)

