合并两个字典

58

给定一些字典

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

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

GroupNames = GroupNames.Concat(AddedGroupNames);

因为“类型无法隐式转换”。我相信(并且我的代码证明了我的想法是正确的),他们的类型是相同的 - 我忽略了什么?


1
可以安全地假设GroupNamesAddedGroupNames之间不会发生键冲突吗? - Sven Grosen
2
这个问题已经在这里得到了回答:https://dev59.com/I3VC5IYBdhLWcg3wcgqd - André Snede
1个回答

121

我认为你将你的GroupNames定义为Dictionary<string,string>,因此你需要像这样添加ToDictionary

GroupNames = GroupNames.Concat(AddedGroupNames)
                       .ToDictionary(x=>x.Key,x=>x.Value);
请注意,两个原始词典会有不同的键,否则我们需要一些规则来正确地合并它们。

6
太好了,与标记为原始的问题中提供的其他答案相比,这个解决方案要简单得多! - Milind Thakkar
7
这是一个不错的解决方案,但唯一的问题在于重复的键。如果存在重复的键,则会抛出异常。 - Saeed Neamati
6
如果存在重复的键,可以使用以下代码: GroupNames = GroupNames.Concat(AddedGroupNames.Where(x => !GroupNames.ContainsKey(x.Key))).ToDictionary(x => x.Key, x => x.Value) - KY Lu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接