如何解决“已添加项目".输入字典:“错误? [英] How can I resolve "Item has already been added. Key in dictionary:" errors?

查看:86
本文介绍了如何解决“已添加项目".输入字典:“错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,当我尝试向其中添加项目时挂断了.当我检查跟踪文件时,我得到了以下条目:

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.

推荐答案

问题是,在排序列表中,每个键都必须是唯一的.因此,您需要检查是否没有两次插入相同的键(引导值).代码如下所示:

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.

这篇关于如何解决“已添加项目".输入字典:“错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆