c# - 查找具有不同类型值的两个字典的并集

标签 c# linq generics collections covariance

问题

using System.Collections.Generic;
using System.Linq;

给定一个基类和 2 个派生类:

class Base{}
class Derived0 : Base{}
class Derived1 : Base{}

我有两本字典,类型为:

IDictionary<String, Derived0> d0 = ...;
IDictionary<String, Derived1> d1 = ...;

我想找到两个字典的并集,其类型应为 IDictionary<String, Base> 。 (我已经知道键在两个字典中都是唯一的,因此我不关心存在重复项时的行为。)


尝试

如果它们是同一类型I could use

var union = d0.Concat(d1);

但这给出了错误(使用 dmcs 编译):

Test.cs(15,20): error CS0411: The type arguments for method `System.Linq.Queryable.Concat<TSource>(this System.Linq.IQueryable<TSource>, System.Collections.Generic.IEnumerable<TSource>)' cannot be inferred from the usage. Try specifying the type arguments explicitly

如果我明确给出 Base作为类型参数:

IDictionary<string, Base> union = d0.Concat<Base>(d1);

它仍然不起作用:

Test.cs(15,42): error CS1928: Type `System.Collections.Generic.IDictionary<string,Derived0>' does not contain a member `Concat' and the best extension method overload `System.Linq.Enumerable.Concat<Base>(this System.Collections.Generic.IEnumerable<Base>, System.Collections.Generic.IEnumerable<Base>)' has some invalid arguments
/usr/lib/mono/gac/System.Core/4.0.0.0__b77a5c561934e089/System.Core.dll (Location of the symbol related to previous error)
Test.cs(15,42): error CS1929: Extension method instance type `System.Collections.Generic.IDictionary<string,Derived0>' cannot be converted to `System.Collections.Generic.IEnumerable<Base>'

原则上,方差在这里并不重要,因为我正在创建一个新的字典对象,但我不知道如何在类型系统中表示它。

最佳答案

IDictionary<TKey, TValue>KeyValuePair<TKey, TValue>不是变体...所以:

var sequence0 = d0.Select(kvp => new KeyValuePair<String, Base>(kvp.Key, kvp.Value));
var sequence1 = d1.Select(kvp => new KeyValuePair<String, Base>(kvp.Key, kvp.Value));
var dictionaryOfBase = sequence0.Concat(sequence1).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

关于c# - 查找具有不同类型值的两个字典的并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13487759/

相关文章:

java - 使用 java 8 流将位字符串转换为枚举数组

typescript - 利用函数输入和输出的通用类型

c# - 泛型内存管理

c# - Kentico 中的多对多关系

c# - 确定控制台输出的结束

c# - 如何通过Linq从xml中获取值

c# - 检查列表是否包含多个指定值

c# - 如何使用 Linq 从列表中提取这些数据?

c# - iTextSharp table.SpacingBefore 不工作

c# - 使用 ListBox 和 StackPanel 的所有可用空间作为 ItemsPanelTemplate