2013-11-22 46 views
26

鉴于一些字典连接两个字典

Dictionary<string, string> GroupNames = new Dictionary<string, string>(); 
Dictionary<string, string> AddedGroupNames = new Dictionary<string, string>(); 

我无法将它们合并为一个:

GroupNames = GroupNames.Concat(AddedGroupNames); 

因为“类型不能被隐式转换”。我相信(和我的代码证明我是真的)他们的类型是一样的 - 我忽略了什么?

+1

假设'GroupNames'和'AddedGroupNames'之间不存在关键冲突是否安全? –

+2

这已经在这里得到解答:http://stackoverflow.com/questions/294138/merging-dictionaries-in-c-sharp –

回答

54

我想你定义你的GroupNamesDictionary<string,string>,所以你需要添加ToDictionary这样的:

GroupNames = GroupNames.Concat(AddedGroupNames) 
         .ToDictionary(x=>x.Key,x=>x.Value); 

注意2个原词典将有不同的密钥,否则,我们需要一些规则,以确保正确合并。

+5

伟大..这是比上面标记作为原始问题给出的其他答案更简单的解决方案! –

+2

这是一个很好的解决方案,但唯一的问题是重复密钥。如果有重复的键,则会抛出异常。 –