参考此answer:
public class DictionaryCollection<TType> : Dictionary<string,Dictionary<string,TType>> {
public void Add(string dictionaryKey,string key, TType value) {
if(!ContainsKey(dictionaryKey))
Add(dictionaryKey,new Dictionary<string, TType>());
this[dictionaryKey].Add(key,value);
}
public TType Get(string dictionaryKey,string key) {
return this[dictionaryKey][key];
}
}
如何通过单独添加它们的值来添加两个(或更多)字典,以使用常见的dictionaryKey和key来获得合并的字典?
例如:
var dictionary1 = new DictionaryCollection<int>
{
{"dic1", "Key1", 1},
{"dic1", "Key2", 2},
{"dic1", "Key3", 3},
{"dic2", "Key1", 1}
};
var dictionary2 = new DictionaryCollection<int>
{
{"dic1", "Key1", 1},
{"dic1", "Key2", 2},
{"dic1", "Key3", 3},
};
合并的字典应为:
mergedDictionary = { {"dic1", "Key1", 2},
{"dic1", "Key2", 4},
{"dic1", "Key3", 6},
{"dic2", "Key1", 1}
};
答案 0 :(得分:-1)
this帮助了我,也许会帮助您。我用它来合并两个字典(Dictionary<string, string>
)
var _merged = _content.Concat(_l)
.ToLookup(x => x.Key, x => x.Value)
.ToDictionary(x => x.Key, g => g.First());