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

瘦欲@ 提交于 2019-12-20 03:47:07

问题


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.


回答1:


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.




回答2:


The exception indicates that you adding same key twice to your dictionary, to solve this issue you can start by insuring that the DataModelCollection objects which passed to the function has unique Key values (which in your case is a Guid data type) dmo.Guid



来源:https://stackoverflow.com/questions/7631789/how-can-i-resolve-item-has-already-been-added-key-in-dictionary-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!