【问题标题】:Concatenate two Dictionaries [duplicate]连接两个字典[重复]
【发布时间】:2013-12-07 16:01:36
【问题描述】:

给定一些字典

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

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

GroupNames = GroupNames.Concat(AddedGroupNames);

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

【问题讨论】:

标签: c# implicit-conversion


【解决方案1】:

我认为您将GroupNames 定义为Dictionary&lt;string,string&gt;,因此您需要像这样添加ToDictionary

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

请注意,两个原始字典会有不同的键,否则我们需要一些规则来正确合并它们。

【讨论】:

  • 太棒了..与上面标记为原始的问题中给出的其他答案相比,这是更简单的解决方案!
  • 这是一个很好的解决方案,但唯一的问题是重复键。如果存在重复键,则会抛出异常。
  • 如果有重复键,使用如下代码GroupNames = GroupNames.Concat(AddedGroupNames.Where( x=&gt; !GroupNames.ContainsKey(x.Key))).ToDictionary(x=&gt;x.Key, x=&gt;x.Value)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
  • 2012-09-12
  • 2013-08-08
  • 2019-10-23
  • 2014-05-20
  • 2010-12-19
相关资源
最近更新 更多