【问题标题】:C# - "An element with the same key was already added"C# - “已添加具有相同键的元素”
【发布时间】:2017-03-24 09:10:36
【问题描述】:

我在 ASP.NET MVC 中工作,我在我的模型中被阻止(包围),出现这个该死的错误“已经添加了具有相同键的元素”,我完全不明白为什么虽然我有几乎相同的代码我模型的其他方法中的不同请求。

而且我不认为问题可能来自请求,因为我已经像以前一样在另一个项目中使用了她(它)。

public Dictionary<string,string> getDonnee()
{
    Dictionary<string, string> list = new Dictionary<string, string>();

    SqlConnection cn;
    SqlDataAdapter da;
    DataSet ds;

    cn = new SqlConnection(CS_DW);
    cn.Open();

    da = new SqlDataAdapter("select distinct(ltrim(rtrim(cpic))) as code, cpic as lib from [DW].[dbo].[PIC_PROD_S001] ", cn);
    ds = new DataSet();
    da.Fill(ds, "code");

    list.Add("REEL", "REEL");
    foreach (DataRow row in ds.Tables["code"].Rows)
    {
        list.Add(row["code"].ToString(), row["lib"].ToString());
    }

    cn.Close();
    return list;
 }

【问题讨论】:

  • 那么你有没有在代码崩溃的地方调试代码?什么是重复键?
  • 可能REEL也存在于数据库中?
  • select distinct 仅根据您的列列表返回不同的行。您的数据集可能会返回带有重复值的代码列。
  • 不要使用Add(),使用TryAdd()
  • 只需在调试器下运行,在异常时停止并检查 row["code"] 的当前值 - 这是重复的。

标签: c# sql asp.net sql-server asp.net-mvc-3


【解决方案1】:

也许你可以测试他们是否已经在你的字典里输入了

if (!list.ContainsKey(row["code"].ToString())) 
{ 
    list.Add(row["code"].ToString(), row["lib"].ToString());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多