当我调试下面的代码时,它总是抛出以下异常:
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/