【问题标题】:Combining multiple dictionaries into one [duplicate]将多个字典组合成一个[重复]
【发布时间】:2018-11-14 21:25:21
【问题描述】:

假设我有两个变量,它们的类型都是Dictionary<int, int>

Dictionary<int, int> d1 = new Dictionary<int, int> { ... };
Dictionary<int, int> d2 = new Dictionary<int, int> { ... };

两个字典可能包含相同的键。

我希望它们合并成一个 Dictionary&lt;int, int&gt; combinedDictionary

有什么优雅的方法可以做到这一点?

我尝试了以下方法:

var combinedDictionary = d1.Concat(d2.Where(x => !d1.Keys.Contains(x.Key)));

但不幸的是,当尝试返回这个组合变量时,我收到以下错误:

无法将表达式类型“System.Collections.Generic.IEnumerable>”转换为返回类型“System.Collections.Generic.Dictionary”。

这样可以安全施放吗?

return (Dictionary<int, int>) combinedDictionary;

提前致谢!

【问题讨论】:

标签: c# .net dictionary


【解决方案1】:

Concat 返回一个IEnumerable&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;。您想调用 ToDictionary 将其转换为字典。

IEnumerable<KeyValuePair<int, int>> combined = d1.Concat(d2.Where(x => !d1.Keys.Contains(x.Key)));
Dictionary<int, int> result = combined.ToDictionary(x => x.Key, x => x.Value);

【讨论】:

  • @SeM 编译器没有说谎。你也可以试试。
  • 哎呀,我没有看到有问题的这部分return (Dictionary&lt;int, int&gt;) combinedDictionary;,对不起,继续。
猜你喜欢
  • 2012-05-20
  • 1970-01-01
  • 2020-07-29
  • 1970-01-01
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
  • 2015-10-04
  • 1970-01-01
相关资源
最近更新 更多