Argument Exception “Item with Same Key has already been added”

后端 未结 6 1583
悲哀的现实
悲哀的现实 2020-12-03 20:38

I keep getting an error with the following code:

Dictionary rct3Features = new Dictionary();
Dictionary

        
相关标签:
6条回答
  • 2020-12-03 21:13

    To illustrate the problem you are having, let's look at some code...

    Dictionary<string, string> test = new Dictionary<string, string>();
    
    test.Add("Key1", "Value1");  // Works fine
    test.Add("Key2", "Value2");  // Works fine
    test.Add("Key1", "Value3");  // Fails because of duplicate key
    

    The reason that a dictionary has a key/value pair is a feature so you can do this...

    var myString = test["Key2"];  // myString is now Value2.
    

    If Dictionary had 2 Key2's, it wouldn't know which one to return, so it limits you to a unique key.

    0 讨论(0)
  • 2020-12-03 21:21

    This error is fairly self-explanatory. Dictionary keys are unique and you cannot have more than one of the same key. To fix this, you should modify your code like so:

    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);
        //}
    }
    

    This simple if statement ensures that you are only attempting to add a new entry to the Dictionary when the Key (items[0]) is not already present.

    0 讨论(0)
  • 2020-12-03 21:21

    Clear the dictionary before adding any items to it. I don't know how a dictionary of one object affects another's during assignment but I got the error after creating another object with the same key,value pairs.

    NB: If you are going to add items in a loop just make sure you clear the dictionary before entering the loop.

    0 讨论(0)
  • 2020-12-03 21:23

    If you want "insert or replace" semantics, use this syntax:

    A[key] = value;     // <-- insert or replace semantics
    

    It's more efficient and readable than calls involving "ContainsKey()" or "Remove()" prior to "Add()".

    So in your case:

    rct3Features[items[0]] = items[1];
    
    0 讨论(0)
  • 2020-12-03 21:28

    As others have said, you are adding the same key more than once. If this is a NOT a valid scenario, then check Jdinklage Morgoone's answer (which only saves the first value found for a key), or, consider this workaround (which only saves the last value found for a key):

    // This will always overwrite the existing value if one is already stored for this key
    rct3Features[items[0]] = items[1];
    

    Otherwise, if it is valid to have multiple values for a single key, then you should consider storing your values in a List<string> for each string key.

    For example:

    var rct3Features = new Dictionary<string, List<string>>();
    var rct4Features = new Dictionary<string, List<string>>();
    
    foreach (string line in rct3Lines)
    {
        string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);
    
        if (!rct3Features.ContainsKey(items[0]))
        {
            // No items for this key have been added, so create a new list
            // for the value with item[1] as the only item in the list
            rct3Features.Add(items[0], new List<string> { items[1] });
        }
        else
        {
            // This key already exists, so add item[1] to the existing list value
            rct3Features[items[0]].Add(items[1]);
        }
    }
    
    // To display your keys and values (testing)
    foreach (KeyValuePair<string, List<string>> item in rct3Features)
    {
        Console.WriteLine("The Key: {0} has values:", item.Key);
        foreach (string value in item.Value)
        {
            Console.WriteLine(" - {0}", value);
        }
    }
    
    0 讨论(0)
  • 2020-12-03 21:28

    That Exception is thrown if there is already a key in the dictionary when you try to add the new one.

    There must be more than one line in rct3Lines with the same first word. You can't have 2 entries in the same dictionary with the same key.

    You need to decide what you want to happen if the key already exists - if you want to just update the value where the key exists you can simply

    rct3Features[items[0]]=items[1]
    

    but, if not you may want to test if the key already exists with:

    if(rect3Features.ContainsKey(items[0]))
    {
        //Do something
    } 
    else 
    {
        //Do something else
    }
    
    0 讨论(0)
提交回复
热议问题