c# - 字典中的 "An item with the same key has already been added"

标签 c# .net dictionary

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

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++;
}

最佳答案

检查正确的 key :

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

代替:

if (!ExistIncInsList.ContainsKey(WSInsName))

关于c# - 字典中的 "An item with the same key has already been added",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14606933/

相关文章:

Python字典打破了python的规律

python - 在 Python 中具有特定顺序的 OrderedDict

c# - MVC3 路由问题

c# - 从 C# API 将 excel 图表中轴的下限和上限设置为数据集的最小值/最大值

c# - 32 位 .NET 最大字节数组大小是否小于 2GB?

c# - 如何在 WPF 应用程序页面而不是窗口中禁用最大化按钮

c# - PurgeTempDestinations 没有实现

ios - 使用日期作为保存到 plist 的字典中的键

c# - 如何检测用户何时单击 WebView 控件中的超链接?

c# - 如何覆盖基类字段功能?