C#のContainsKey
containsKeyはC#のディクショナリメソッドであり、キーがディクショナリに存在するかどうかを確認します。
辞書を宣言して要素を追加する-
var dict = new Dictionary<string, int>() {
{"TV", 1},
{"Home Theatre", 2},
{"Amazon Alexa", 3},
{"Google Home", 5},
{"Laptop", 5},
{"Bluetooth Speaker", 6}
}; ここで、辞書に特定の要素が存在するかどうかを確認する必要があるとします。そのためには、ContainsKey()メソッドを使用します-
if (dict.ContainsKey("Laptop") == true) {
Console.WriteLine(dict["Laptop"]);
} 以下はコードです-
例
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
var dict = new Dictionary<string, int>() {
{"TV", 1},
{"Home Theatre", 2},
{"Amazon Alexa", 3},
{"Google Home", 5},
{"Laptop", 5},
{"Bluetooth Speaker", 6}
};
if (dict.ContainsKey("Laptop") == true) {
Console.WriteLine(dict["Laptop"]);
}
if (dict.ContainsKey("Amazon Alexa") == true) {
Console.WriteLine(dict["Amazon Alexa"]);
}
}
} 出力
5 3
-
C#のContainsKey()メソッド
ハッシュテーブルコレクションを設定し、それにいくつかの要素を追加します。 Hashtable h = new Hashtable(); h.Add(1, "Sam"); h.Add(2, "Jack"); h.Add(3, "Andy"); h.Add(4, "Katie"); h.Add(5, "Beth"); h.Add(6, "Benjamin"); containsKey()メソッドを使用して、キーがハッシュテーブルに存在するかどうかを確認します。 キー3を確認し
-
C#のContainsKey
containsKeyはC#のディクショナリメソッドであり、キーがディクショナリに存在するかどうかを確認します。 辞書を宣言して要素を追加する- var dict = new Dictionary<string, int>() { {"TV", 1}, {"Home Theatre", 2}, {"Amazon Alexa", 3}, {"Google Home", 5},