我不断收到以下代码的错误:
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
说,
"An item with the same key has already been added."
经过多次 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, 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);
if (!rct3Features.ContainsKey(items[0]))
{
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);
//}
}
这个简单的 if
语句确保您仅在键 (items[0]
) 不存在时才尝试向字典添加新条目。
关于c# - 参数异常 "Item with Same Key has already been added",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26516825/