【发布时间】:2011-06-15 02:00:56
【问题描述】:
我正在测试 UNION 方法以合并到字典(字典类型)。它适用于 TValue 类型是 string 或 int 甚至是 object。但如果 TValue 类型是一个集合(使用 List 和 object[] 测试),则会引发异常:"ArgumentException: An item with the same key has 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);
为什么行为不一样?以及如何解决这个问题?
谢谢!
【问题讨论】:
标签: c# dictionary merge union