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