C#のDictionaryでキーがあるかどうかを確認するにはContainsKey()を使います。下記はコード例です
var dic = new Dictionary<string,string>{ {"名称", "ハインライン"} }; if(dic.ContainsKey("名称")){ //"名称"というキーがあるかどうか Console.WriteLine(dic["名称"]); }
キーが無い場合dic[“名称”]とすると下記のようなエラーがでました。
例外が発生しました: CLR/System.Collections.Generic.KeyNotFoundException 型 'System.Collections.Generic.KeyNotFoundException' のハンドルされていない例外が System.Private.CoreLib.dll で発生しました: 'The given key '名称' was not present in the dictionary.'
その場合TryGetValue()を使って取得もできるのですがあまりメリットを感じない
var dic = new Dictionary<string,string>{ {"名称", "ハインライン"} }; string outstr = ""; if (dic.TryGetValue("名称",out outstr)) Console.WriteLine(outstr);
Dictionaryキーが無い場合TryGetValue()で試すとout TValueの中身がnullになるようでした。
Dictionary キー一覧取得
var dic = new Dictionary<string,string>{ {"名称", "ハインライン"} }; foreach(var a in dic.Keys){ Console.WriteLine("{0}={1}",a,dic[a]); }
上記コードのようにKeysを使えばキー一覧(KeyCollection)を取得できます。