How can I resolve "Item has already been added. Key in dictionary:" errors?

user972380 picture user972380 · Oct 3, 2011 · Viewed 42.7k times · Source

I have an application which got hung up when I tried to add items to it. When I checked the trace file I got this entry:

   for (int i=0; i<objects.Count; i++) 
   {
      DataModelObject dmo = (DataModelObject)objects.GetAt(i);
      sl.Add(dmo.Guid, dmo);
   }

}

I don't know how to solve this issue.

Answer

Kevin Holditch picture Kevin Holditch · Oct 3, 2011

The problem is that in a sorted list each key needs to be unique. So you need to check that you aren't inserting the same key (guid value) twice. Code shown below:

 for (int i=0; i<objects.Count; i++) 
 {        
    DataModelObject dmo = (DataModelObject)objects.GetAt(i);

    if (!sl.ContainsKey(dmo.Guid))
    {
        sl.Add(dmo.Guid, dmo);
    }
 }

This will ensure that each key is unique. If however you are expecting more than one value for each key then you need to use a different type of collection.