【发布时间】:2014-12-18 10:56:55
【问题描述】:
我不断收到以下代码错误:
Dictionary<string, string> rct3Features = new Dictionary<string, string>();
Dictionary<string, string> rct4Features = new Dictionary<string, string>();
foreach (string line in rct3Lines)
{
string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);
rct3Features.Add(items[0], items[1]);
////To print out the dictionary (to see if it works)
//foreach (KeyValuePair<string, string> item in rct3Features)
//{
// Console.WriteLine(item.Key + " " + item.Value);
//}
}
错误抛出ArgumentException 说,
“已添加具有相同密钥的项目。”
经过多次 Google 搜索后,我不确定如何解决此问题。
稍后在代码中我需要访问字典以获得比较功能:
Compare4To3(rct4Features, rct3Features);
public static void Compare4To3(Dictionary<string, string> dictionaryOne, Dictionary<string, string> dictionaryTwo)
{
//foreach (string item in dictionaryOne)
//{
//To print out the dictionary (to see if it works)
foreach (KeyValuePair<string, string> item in dictionaryOne)
{
Console.WriteLine(item.Key + " " + item.Value);
}
//if (dictionaryTwo.ContainsKey(dictionaryOne.Keys)
//{
// Console.Write("True");
//}
//else
//{
// Console.Write("False");
//}
//}
}
此功能尚未完成,但我正在尝试解决此异常。有哪些方法可以修复此异常错误,并保持对字典的访问权限以与此功能一起使用?谢谢
【问题讨论】:
-
停止尝试使用相同的键添加多个项目。也许您应该在添加时添加检查以确保密钥不存在。否则,我们无法知道正确的行动方案是什么,因为您几乎没有提供任何信息来说明如果存在重复项目,您希望发生什么。
-
为什么会有重复的键?如果每个键需要多个值,则应使用
Dictionary<string, List<string>>。 -
在下面查看我的答案以获取更多详细信息,但您可以用不同的语法替换您的 Add 。如果键已存在,则以下内容只会覆盖键的现有值:
rct3Features[items[0]] = items[1];
标签: c# exception dictionary