[英]Dictionary Unhandled Exception in C#: “The given key was not present in the dictionary”
我正在嘗試用C#打印出一個字典來模擬圖形。 我的字典看起來像這樣:
Dictionary<int, List<int>> graph = new Dictionary<int, List<int>>();
總的來說,我在字典中添加了一些內容,然后嘗試將其打印出來:
dicOfLists myDic = new dicOfLists();
myDic.AddEdge(1, 2);
myDic.printList();
AddEdge
和PrintList
方法非常簡單:
AddEdge:
public void AddEdge(int v1, int v2)
{
if (graph[v1] == null)
{
graph[v1] = new List<int> { v2 };
return;
}
graph[v1].Add(v2);
}
的printList:
for (int i = 0; i < 1; i++)
{
Console.WriteLine(graph[i][i]);
}
我沒有用C#或Python做很多編程工作,所以字典對我來說是新的。 我認為為什么被絆倒比什么都更具概念性,特別是因為我不確定列表在字典中的工作方式。
我目前的理解如下:
調用Addedge(1, 2)
我的字典將在我的字典的位置1
處創建一個帶有單個元素2
的列表。 這是因為第一個參數代表字典的鍵,第二個參數代表列表。 像哈希表中那樣的關鍵功能。 提供密鑰后,字典將在該位置查找,然后創建一個列表。
就像我說的那樣,我是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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.