C#에서 Dictionary 컬렉션에 특정 키가 존재하는지 확인하려면 ContainsKey() 메서드를 사용합니다. 이 메서드는 키가 존재하면 True를, 존재하지 않으면 False를 반환합니다.
Dictionary 컬렉션 선언하기
먼저 요소를 포함하는 Dictionary 컬렉션을 설정합니다.
Dictionary<int, string> d = new Dictionary<int, string>() {
{1, "Electronics"},
{2, "Clothing"},
{3, "Toys"},
{4, "Footwear"},
{5, "Accessories"}
};ContainsKey() 메서드로 키 확인하기
예를 들어, 키 5가 존재하는지 확인해야 한다고 가정해 보겠습니다. 이때 ContainsKey() 메서드를 사용하며, 키를 찾으면 True를 반환합니다.
d.ContainsKey(5);
전체 예제 코드
다음은 Dictionary의 모든 요소를 출력한 후, 키 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
정리
ContainsKey() 메서드는 Dictionary에서 키의 존재 여부를 빠르게 확인할 수 있는 효율적인 방법입니다. 내부적으로 해시 기반 조회를 사용하기 때문에 O(1)에 가까운 성능을 제공하며, 존재하지 않는 키에 접근할 때 발생할 수 있는 KeyNotFoundException 예외를 사전에 방지하는 데도 유용하게 활용됩니다.