gpt4 book ai didi

c# - 使用 Enumerable.Union 方法合并 Dictionary

转载 作者:太空狗 更新时间:2023-10-29 20:11:41 25 4
gpt4 key购买 nike

我正在测试 UNION 方法以合并到字典(字典类型)。它适用于 TValue 类型是字符串或 int 甚至对象。但是,如果 TValue 类型是一个集合(使用 List 和 object[] 进行测试),则会抛出异常:"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);

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

谢谢!

最佳答案

在第一种情况下,联合会丢弃重复的键,因为键/值对本身是相等的。在第二种情况下,它们不是,因为 List<String>{"one"}不等于另一个 List<string>{"one"} .

我怀疑你想要你的 Union打电话使用 IEqualityComparer它只考虑字典中的键。

关于c# - 使用 Enumerable.Union 方法合并 Dictionary<TKey, TValue>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4791931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com