ContainsKey는 C#의 Dictionary 메소드이며 Dictionary에 키가 있는지 확인합니다.
사전 선언 및 요소 추가 -
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