【问题标题】:the given key was not present in the dictionary error debugging字典错误调试中不存在给定的键
【发布时间】:2019-09-05 05:19:37
【问题描述】:

当我调试以下代码时,它总是抛出以下异常:

给定的键不在字典中。

我需要帮助解决这个问题。

string current;
Dictionary<string, List<int>> map = new Dictionary<string, List<int>>();

for (int i = 0; i < y; i++){
    current = lines[i].material.Text + "," + lines[i].profilid.Text;
    if (map[current] == null){
        map[current] = new List<int>();
    }  
    map[current].Add(i);
    material_profile.Add(current);
 }

foreach (KeyValuePair<string, List<int>> entry in map){
    List<int> lenghts = new List<int>();
    // do something with entry.Value or entry.Key
    for (int i = 0; i < entry.Value.Count(); i++){
        int stueckzahl = int.Parse(lines[entry.Value[i]].stueck.Text);
        int laenge = int.Parse(lines[entry.Value[i]].länge.Text);

        for (int j = 0; j < stueckzahl; j++){
            lenghts.Add(laenge);
        }
    }
}

【问题讨论】:

    标签: c# dictionary


    【解决方案1】:

    代码map[current] == null 尝试从map[current] 获取值,如果没有项目,这将引发错误。

    如果您想尝试获取可能不存在的项目,您需要使用TryGetValue 方法。

    这将起作用:

        List<int> list;
        if (!(map.TryGetValue(current, out list)))
        {
            list= new List<int>();
            map.Add(current, list);
        }
        list.Add(i);
    

    【讨论】:

      【解决方案2】:

      作为Andrew Shepherd pointed out,您无法查找Dictionary 中不存在的值。

      为了使您的测试有意义,您必须期望 map[current] 实际返回值 null,但这需要字典实际包含一个键值对,其中键与 @ 的值相同987654325@,值为null。在您的情况下,该密钥根本不存在。

      解决您的问题的最简单方法可能是替换此行...

      if (map[current] == null)
      

      ...带有以下内容:

      if (!map.ContainsKey(current))
      

      如果没有找到,它将搜索密钥而不抛出异常。


      PS:您也可以在前一行使用map.Add(current, new List&lt;int&gt;); 而不是[]-syntax - 我个人认为使用.Add(..) 会使代码更简单一些,但这可能是一个偏好问题.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-18
        • 1970-01-01
        • 2016-08-14
        相关资源
        最近更新 更多