【问题标题】:"An item with the same key has already been added" in dictionary字典中的“已添加具有相同键的项目”
【发布时间】:2013-01-14 10:36:06
【问题描述】:

我的 C# 代码有问题。 我不断收到错误消息“已添加具有相同密钥的项目”,我尝试了网上建议的各种方法,但似乎无法摆脱它。 有人可以帮忙吗。 我在这一行得到错误

ExistIncInsList.Add(WSIncInstOutput[Insrow][0], Int32.Parse(WSIncInstOutput[Insrow][1]));

下面是涉及到这个的部分代码。

卡拉博

Dictionary<string, int> ExistIncInsList = new Dictionary<string, int>();
for (int Insrow = 2; Insrow < WSIncInstOutput.Count(); Insrow++)
{
    int existincWSInsID = Int32.Parse(WSIncInstOutput[Insrow][1]);
    if (!ExistIncInsList.ContainsKey(WSInsName))
    {
         ExistIncInsList.Add(WSIncInstOutput[Insrow][0], Int32.Parse(WSIncInstOutput[Insrow][1]));
    }
    if (MaxIncIndID < existincWSInsID)
    {
        MaxIncIndID = existincWSInsID;
        if (MaxIncIndID > MaxIndID)
        {
            MaxIndID = MaxIncIndID;
        } 
     }
}

if (ExistIncInsList.ContainsKey(WSInsName))
{
    WSInsID = ExistIncInsList[WSInsName];
}
else
{
    WSInsID = MaxIndID + 1;
    MaxIndID++;
}

【问题讨论】:

  • 你从哪里得到错误?你能显示一个示例输出吗? ...
  • 您能否发布一些您希望使用此代码实现的示例字典项目。
  • 我已经编辑了我的问题以显示触发错误消息的部分。

标签: c# .net dictionary


【解决方案1】:

检查正确的密钥:

if (!ExistIncInsList.ContainsKey(WSIncInstOutput[Insrow][0]))

代替:

if (!ExistIncInsList.ContainsKey(WSInsName))

【讨论】:

    猜你喜欢
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多