c# - C# 中的字典未处理异常:“字典中不存在给定的键”
问题描述
我正在尝试在 C# 中打印出一个模拟图形的字典。我的字典是这样的:
Dictionary<int, List<int>> graph = new Dictionary<int, List<int>>();
主要是,我在字典中添加了一些内容,然后尝试将其打印出来:
dicOfLists myDic = new dicOfLists();
myDic.AddEdge(1, 2);
myDic.printList();
方法AddEdge
和PrintList
非常简单:
添加边缘:
public void AddEdge(int v1, int v2)
{
if (graph[v1] == null)
{
graph[v1] = new List<int> { v2 };
return;
}
graph[v1].Add(v2);
}
打印清单:
for (int i = 0; i < 1; i++)
{
Console.WriteLine(graph[i][i]);
}
我没有用 C# 或 Python 做过很多编程,所以字典对我来说是新的。我认为我被绊倒的原因比任何事情都更具概念性,特别是因为我不确定列表在字典中是如何工作的。
我目前理解的方式如下:
在调用我的字典时,会在我的字典位置Addedge(1, 2)
创建一个包含单个元素的列表。这是因为第一个参数代表字典的键,第二个参数代表列表。关键功能就像它在哈希表中一样。提供密钥后,字典会查看该位置,然后创建一个列表。2
1
就像我说的,我是 C# 的新手,所以请不要太用力地抨击我。虽然这可能像一个简单的语法错误一样微不足道,但我无法在网上找到很多关于这个特定问题的任何东西。任何帮助将不胜感激!
解决方案
您有一种方法将键/值添加到字典中,另一种方法打印它们。打印它们的方法不“知道”插入了什么,所以如果该方法不对字典中的内容做出任何假设会更好。与其只是遍历一系列可能的键(0 到 1、0 到n等),不如根据字典中的实际内容进行操作。
var keys = graph.Keys;
// or, if you they were entered out of sequence and you want to sort them
var keys = graph.Keys.OrderBy(k => k);
// Now you're using the actual keys that are in the dictionary, so you'll never
// try to access a missing key.
foreach(var key in keys)
{
// It's not quite as clear to me what you're doing with these objects.
// Suppose you wanted to print out everything:
Console.WriteLine($"Key: {key}");
foreach(var value in graph[key])
{
Console.WriteLine(value);
}
}
推荐阅读
- c# - 在字典初始值设定项语法 C# 中访问类变量
- c++ - 以 Eigen::Vector 为参数
- javascript - 如何在 React Hooks 中更改 Provider 的值
- javascript - 我怎样才能在我的代码中只显示我想要的文本?
- oracle - 带有 UPDATE OF 的 Oracle 触发器(列名与表相同)
- c++ - 如何在 C++ 中创建一个空向量?
- c# - 如何打开从 Visual Studio 2019 创建的解决方案文件到使用 Visual Studio 2017 的不同计算机?
- python - 如何编写两个同名的类
- tensorflow - 计算 TensorFlow 中多个类的平均和分类精度/召回率
- python - Google AppEngine - 使用 max_concurrent_requests 设置为 1 的队列:由于超过了请求截止日期,进程终止