关于c#:将多个词典合并为一个词典


Combine multiple dictionaries into a single dictionary

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Merging dictionaries in C#

词典1P></

"a","1"
"b","2"

词典2P></

"c","3"
"d","4"

字典3P></

"e","5"
"f","6"

联合词典P></

"a","1"
"b","2"
"c","3"
"d","4"
"e","5"
"f","6"

如何给组合the above 3进入单打联合字典词典吗?P></


1
2
3
4
5
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);

编辑要确保没有重复的密钥,请使用:

1
2
var result = d1.Concat(d2).Concat(d3).GroupBy(d => d.Key)
             .ToDictionary (d => d.Key, d => d.First().Value);


只需循环它们:

1
2
3
4
5
6
7
var result = new Dictionary<string, string>();

foreach (var dict in dictionariesToCombine) {
    foreach (var item in dict) {
        result.Add(item.Key, item.Value);
    }
}

(假设dictionariesToCombine是您的字典中要组合的IEnumerable,例如数组。)