The given key was not present in the dictionary の原因と直し方
Dictionaryに登録されていないキーをインデクサで読み取ろうとすると発生します。
エラーメッセージの読み方
Unhandled exception. System.Collections.Generic.KeyNotFoundException: The given key 'bob' was not present in the dictionary.
System.Collections.Generic- 名前空間 — System なら標準の基本例外です
KeyNotFoundException- 例外クラス — 何が起きたか。ここを検索するのが最短です
The given key 'bob' was not present in the dictionary.- 詳細メッセージ — どの値が問題だったか
at Program.Main(String[] args) in Program.cs:line 5- 発生箇所 — スタックトレースの先頭行
このエラーが出る典型パターン
パターン1
1 class Program { 2 static void Main(string[] args) { 3 var scores = new System.Collections.Generic.Dictionary<string, int>(); 4 scores["alice"] = 90; 5 System.Console.WriteLine(scores["bob" ]); ^ 6 } 7 }
Unhandled exception. System.Collections.Generic.KeyNotFoundException: The given key 'bob' was not present in the dictionary.
at Program.Main(String[] args) in Program.cs:line 5
存在しないキーで読み取ろうとするとKeyNotFoundExceptionになります。あるかどうかはContainsKeyかTryGetValueで確認します。
直し方: "bob" を "alice" にします。
広告
広告スロット(未設定)
パターン2
1 class Program { 2 static void Main(string[] args) { 3 var names = new System.Collections.Generic.Dictionary<int, string>(); 4 names[1] = "Taro"; 5 System.Console.WriteLine(names[2 ]); ^ 6 } 7 }
Unhandled exception. System.Collections.Generic.KeyNotFoundException: The given key '2' was not present in the dictionary.
at Program.Main(String[] args) in Program.cs:line 5
キーの型が数値でも規則は同じです。登録していない番号を指定すると例外になります。
直し方: 2 を 1 にします。
パターン3
1 class Program { 2 static void Main(string[] args) { 3 var prices = new System.Collections.Generic.Dictionary<string, int>(); 4 prices["apple"] = 100; 5 System.Console.WriteLine(prices["banana"]); ^ 6 } 7 }
Unhandled exception. System.Collections.Generic.KeyNotFoundException: The given key 'banana' was not present in the dictionary.
at Program.Main(String[] args) in Program.cs:line 5
大文字小文字も区別されます。"apple"と"Apple"は別のキーとして扱われます。
直し方: "banana" を "apple" にします。
よくある誤解
存在確認をせずにいきなり読み取ると危険です。ContainsKeyやTryGetValueで事前に確認する習慣が必要です。
まとめ
The given key was not present in the dictionaryは中級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。