c# - 字典错误调试中不存在给定的键

标签 c# dictionary

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

The given key was not present in the dictionary.

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

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

最佳答案

代码 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);

关于c# - 字典错误调试中不存在给定的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57798858/

相关文章:

c# - 在windows phone项目中使用可移植类库

编辑字典列表的 Pythonic 方式

python - 操作字典中的集合

c# - 为什么将长度为 0 的 byte[] 注入(inject)到我的类中?

c# - 确定 double 是否不为零的最佳方法是什么

python - 具有权重 Python 的节点对出现率

java - 榛卡斯特 map : remove entries owned by the node that goes down

python - 将字典值映射到列表

c# - 传递日期参数以将日期存储在 C# 中的对象变量中

c# - 异常捕获最佳实践 (c#/.net)