I am trying
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;
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.
Assumption #1:
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.Dictionary requires that each key (the first parameter to
Add()) is unique, howeverCmd.Parameters["@ReturnVal"]looks suspiciously like it is theParametersproperty of anSqlCommand(or one of its parent classes). If so, it will always return the same value in the code you show.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 likeList<Tuple<int, int>>instead.Example:
Assumption #2:
Actually, the
IDList[i]values (again, as the name suggests) are the unique values, i.e. your keys, and you simply have theDictionary<TKey,TValue>.Add()parameters the wrong way around.