参数例外:“已添加具有相同密钥的项目” [英] Argument Exception: "An item with the same key has already been added"

查看:334
本文介绍了参数例外:“已添加具有相同密钥的项目”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序在我尝试添加项目时挂起。



我收到运行时错误:



已添加具有相同密钥的项目。



I have an application which got hung when i tried to add items to it.

I get a runtime error:

An item with the same key has already been added.

  private class ProductUpdate
        {
            public int Index = 0;
            public string ProductCode;
        }
private void UpdateProduct( List<string> account, string userEmail, 
List<Product> products )
   {
Dictionary<string, ProductUpdate> productUpdateDictionary = new Dictionary<string, ProductUpdate>();

            for ( int i = 0; i < products.Count; i++ )
            {
       productUpdateDictionary.Add( products[i].code, new ProductUpdate { Index = i, ProductCode = products[i].code } );
            }
}





我不知道如何解决这个问题,任何机构都有任何建议

非常感谢!



I don't know how to solve this issue ,any body has any suggestion
Thanks a lot!

推荐答案

您发布的代码中没有错误。问题可能是概念类型,也可能代码是调用 UpdateProduct(..)的代码。



In这一行:
There's no bug in the code that you posted. The problem is either of conceptual kind or lies in the code that calls UpdateProduct(..).

In this line:
productUpdateDictionary.Add( products[i].code, new ProductUpdate { Index = i, ProductCode = products[i].code } );

你的代码正在填充一个Dictionary。字典只允许添加唯一键。方法参数 List< Product>中的一个或多个 Product s产品具有相同的代码 s,这就是这里例外的原因。


修改:<>麻烦

your code is populating a Dictionary. A Dictionary only ever allows unique keys to be added. One or more Products in the method-argument List<Product> products have identical codes and that's the cause of the exception here.

<> troubles


请阅读我对这个问题的评论。



A 字典 [ ^ ]不允许两次添加相同的值。您需要通过添加尝试...抓住......最后 [ ^ ]阻止。
Please, read my comment to the question.

A dictionary[^] does not allow to add the same value twice. You need to handle it by adding Try... Catch... Finally[^] block.


在为密钥添加值之前,您必须检查密钥是否已存在。你必须这样做。



You have to check if a key already exists before adding a value for the key. You have to do as follows.

if (!productUpdateDictionary.Contains(products[i].code)){
    productUpdateDictionary.Add(products[i].code, new ProductUpdate { Index = i, ProductCode = products[i].code });
}


这篇关于参数例外:“已添加具有相同密钥的项目”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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