合并字典< TKEY的,TValue>与Enumerable.Union方法
我测试在 UNION 方式合并到词典(型词典)。与TValue类型为字符串或诠释,甚至反对它工作正常。但是,如果TValue类型是集合(与名单测试对象[])抛出一个异常:的ArgumentException:使用相同的密钥已经被添加的项目
I'm testing the UNION method to merge to dictionaries (of type Dictionary). It works fine with TValue type is string or int or even object. But if TValue type is a collection (tested with List and object[]) an exception is thrown : "ArgumentException: An item with the same key has already been added."
下面是我的代码:
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);
为什么行为是不一样的?如何解决这个问题呢?
Why the behavior is not the same ? And How to resolve this problem ?
感谢您!
在第一种情况下,由于键/值对本身是相等联盟丢弃重复键。在第二种情况下他们不是,因为列表<弦乐> {一}
不等于另一个列表<串> { 一}
。
In the first case, the Union is discarding the duplicate keys because the key/value pairs themselves are equal. In the second case they're not, because a List<String>{"one"}
isn't equal to another List<string>{"one"}
.
我怀疑你希望你的联盟
来电使用的IEqualityComparer
只考虑字典中的所有键。
I suspect you want your Union
call to use an IEqualityComparer
which only takes account of the keys within the dictionary.