合并字典< TKEY的,TValue>与Enumerable.Union方法 [英] Merge Dictionary<TKey, TValue> with Enumerable.Union method

查看:159
本文介绍了合并字典< 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.

这篇关于合并字典&LT; TKEY的,TValue&GT;与Enumerable.Union方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆