添加项字典显示错误:具有相同的键的项已被添加。字典 [英] Adding item in dictionary showing an error: an item with the same key has already been added. dictionary

查看:190
本文介绍了添加项字典显示错误:具有相同的键的项已被添加。字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想

   Dictionary<int, int> list = new Dictionary<int, int>();

   for (int i = 0; i < IDList.Count; i++)
   {
     list.Add(Convert.ToInt32(Cmd.Parameters["@ReturnVal"].Value.ToString()), IDList[i]);
   }
   return list;

当我ADDI一个值的两倍,没有错误,但第三次它显示的误差

When I addi a value twice there is no error but the third time it shows the error

具有相同的键的项已被添加。字典

an item with the same key has already been added. dictionary

有人请告诉我怎么解决这个问题。

Someone please tell me how to solve this.

推荐答案

假设1:

你的名字你的词典名单,这意味着,你没有使用字典这是什么包换,应该有可能使用一个列表&LT; T&GT; 而不是

You name your dictionary "list", which suggests, you are not using a dictionary for what it was ment for and should possibly be using a List<T> instead.

字典要求每个键(第一个参数添加())是唯一的,但 Cmd.Parameters [@ ReturnVal] 看起来很像是的参数属性的的SqlCommand (或它的父类中的一个)。如果是这样,它总是返回相同的值在code告诉你。

Dictionary requires that each key (the first parameter to Add()) is unique, however Cmd.Parameters["@ReturnVal"] looks suspiciously like it is the Parameters property of an SqlCommand (or one of its parent classes). If so, it will always return the same value in the code you show.

所以,如果你真的想创建一个元组的集合,其中第一个值始终是@ReturnValue,第二个值 IDList表[I] ,那么你应该使用类似列表与LT元组LT; INT,INT&GT;方式&gt; 而不是

So, if you really want to create a collection of tuples where the first value always is "@ReturnValue" and the second value is IDList[i], then you should use something like List<Tuple<int, int>> instead.

例如:

  List<Tuple<int, int>> list = new List<Tuple<int, int>>();

  for (int i = 0; i < IDList.Count; i++)
  {
    list.Add(
      Tuple.Create(Convert.ToInt32(Cmd.Parameters["@ReturnVal"].Value), IDList[i])
    );
  }

  return list;

假设2:

其实, IDList表[I] 值(再次,顾名思义)是唯一值,也就是你的钥匙,你只需在字典&LT; TKEY的,TValue&GT;。新增()参数周围的错误的方式。

Actually, the IDList[i] values (again, as the name suggests) are the unique values, i.e. your keys, and you simply have the Dictionary<TKey,TValue>.Add() parameters the wrong way around.

这篇关于添加项字典显示错误:具有相同的键的项已被添加。字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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