使用Enumerable.Union方法合并字典<TKey,TValue>

Flo*_*ian 7 c# union merge dictionary

我正在测试UNION方法以合并到字典(类型为Dictionary).它适用于TValue类型是字符串或int甚至对象.但是如果TValue类型是一个集合(使用List和object []测试),则抛出异常:"ArgumentException:已经添加了具有相同键的项目."

这是我的代码:

Dictionary<int,string> _dico1 = new Dictionary<int, string>()
{
    {0, "zero"},
    {1, "one"}
};

Dictionary<int,string> _dico2 = new Dictionary<int,string>()
{
    {1 , "one"},
    {2 , "two"},
    {3 , "three"},
    {4 , "four"},
    {5 , "five"},
    {6 , "six"}
};

Dictionary<int, List<string>> _dico3 = new Dictionary<int, List<string>>()
{
    {0, new List<string>{"zero"}},
    {1, new List<string>{"one"}}
};

Dictionary<int, List<string>> _dico4 = new Dictionary<int, List<string>>()
{
    {1, new List<string>{"one"}},
    {2, new List<string>{"two"}},
    {3, new List<string>{"three"}},
    {4, new List<string>{"four"}},
    {5, new List<string>{"five"}},
    {6, new List<string>{"six"}},
};

    // works fine
    var mergeDico = _dico1.Union(_dico2).ToDictionary(key => key.Key, value => value.Value);

    // throw an ArgumentException : An item with the same key has already been added
    var mergeDico2 = _dico3.Union(_dico4).ToDictionary(key => key.Key, value => value.Value);
Run Code Online (Sandbox Code Playgroud)

为什么行为不一样?以及如何解决这个问题?

谢谢 !

Jon*_*eet 7

在第一种情况下,Union正在丢弃重复键,因为键/值对本身是相等的.在第二种情况下,他们不是,因为a List<String>{"one"}不等于另一种List<string>{"one"}.

我怀疑你希望你的Union呼叫使用IEqualityComparer只考虑字典中的密钥的呼叫.

  • @Florian:这不是直接归因于不变性 - 这是由于涉及的类型是否具有值等同语义.您仍然可以使用不可执行的类型. (5认同)