먼저 요소가 있는 Dictionary 컬렉션을 설정합니다.
Dictionary<int, string> d = new Dictionary<int, string>() {
{1,"Applianes"},
{2, "Clothing"},
{3,"Toys"},
{4,"Footwear"},
{5, "Accessories"}
}; 이제 키 5가 있는지 여부를 확인해야 한다고 가정해 보겠습니다. 이를 위해 ContainsKey() 메서드를 사용합니다. 키를 찾으면 True를 반환합니다.
d.ContainsKey(5);
전체 코드를 살펴보겠습니다.
예
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
Dictionary<int, string> d = new Dictionary<int, string>() {
{1,"Electronics"},
{2, "Clothing"},
{3,"Toys"},
{4,"Footwear"},
{5, "Accessories"}
};
foreach (KeyValuePair<int, string> ele in d) {
Console.WriteLine("Key = {0}, Value = {1}", ele.Key, ele.Value);
}
Console.WriteLine("Key 5 exists? "+d.ContainsKey(5));
}
} 출력
Key = 1, Value = Electronics Key = 2, Value = Clothing Key = 3, Value = Toys Key = 4, Value = Footwear Key = 5, Value = Accessories Key 5 exists? True