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

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

I keep getting an error with the following code:

Dictionary rct3Features = new Dictionary();
Dictionary

        
6条回答
  •  挽巷
    挽巷 (楼主)
    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 for each string key.

    For example:

    var rct3Features = new Dictionary>();
    var rct4Features = new Dictionary>();
    
    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 { 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> item in rct3Features)
    {
        Console.WriteLine("The Key: {0} has values:", item.Key);
        foreach (string value in item.Value)
        {
            Console.WriteLine(" - {0}", value);
        }
    }
    

提交回复
热议问题