Dictionaryに指定したKeyが含まれているかの判別とValueを取得する方法に「TryGetValue」メソッドがあります。
サンプルコードを交えて解説したいと思います。
例
コード
using System; using System.Collections.Generic; namespace Sample { /// <summary> /// メインプログラム /// </summary> public class Program { /// <summary> /// Dictionaryに指定したKeyが含まれているかの判別とValueの取得 /// </summary> static void Main() { // Dictionaryの生成 var pairs = new Dictionary<int, string>(); // 要素を追加 pairs.Add(1, "一郎"); pairs.Add(2, "二郎"); pairs.Add(3, "三郎"); // 指定したKeyが含まれているかの判別とValueの取得 bool hasKey1 = pairs.TryGetValue(1, out string? value1); bool hasKey2 = pairs.TryGetValue(100, out string? value2); Console.WriteLine("Keyに1は含まれている : " + hasKey1); Console.WriteLine("Keyが1のValue : " + value1); Console.WriteLine("Keyに100は含まれている : " + hasKey2); Console.WriteLine("Keyが100のValue : " + value2); } } }
出力
Keyに1は含まれている : True Keyが1のValue : 一郎 Keyに100は含まれている : False Keyが100のValue :