c# - 参数异常 "Item with Same Key has already been added"

标签 c# exception dictionary

我不断收到以下代码的错误:

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/

相关文章:

cocoa - "EXC_BREAKPOINT (SIGTRAP)"异常是否是调试断点导致的?

java - 如果我有索引,则从映射中获取键或值

python - 从 2 元组列表创建字典

c# - 从资源文件读取 Cursor 时抛出 ArgumentException

c# - 正则表达式 - 双引号到 xml 标签中的双引号转义

c# - (什么时候)使用 FluentAssertions 是个好主意?

c# - 在 WPF TabControl 中托管外部应用程序

java - 使用 @ControllerAdvice 注释的类处理异常时丢失堆栈跟踪

javascript - 如何检查ApolloError是否是由客户端网络连接引起的?

python - Pandas 错误 : __setitem__() doesnt recognize dictionary values as a list of column names