C#에서 Dictionary<TKey,TValue> 컬렉션에 특정 키가 존재하는지 확인하려면 ContainsKey() 메서드를 사용합니다. 이 메서드는 지정한 키가 딕셔너리에 있으면 true, 없으면 false를 반환합니다.
예제 1: 존재하는 키 확인
다음 예제는 딕셔너리에 "Three"라는 키가 있는지 확인하는 코드입니다.
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("요소 개수 = " + dict.Count);
Console.WriteLine("\n키/값 쌍 출력...");
foreach(KeyValuePair<string, string> res in dict) {
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
if (dict.ContainsKey("Three"))
Console.WriteLine("키를 찾았습니다!");
else
Console.WriteLine("해당 키는 딕셔너리에 없습니다!");
dict.Clear();
Console.WriteLine("삭제 후 키/값 쌍 출력...");
foreach(KeyValuePair<string, string> res in dict) {
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("현재 요소 개수 = " + dict.Count);
}
}출력 결과
Count of elements = 5 Key/value pairs... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan Key found! Cleared Key/value pairs... Count of elements now = 0
위 실행 결과에서 볼 수 있듯이, "Three"라는 키가 딕셔너리에 존재하기 때문에 ContainsKey() 메서드가 true를 반환하여 "키를 찾았습니다!"라는 메시지가 출력됩니다. 이후 Clear() 메서드로 모든 요소를 삭제하면 요소 개수가 0이 됩니다.
예제 2: 존재하지 않는 키 확인
이번에는 딕셔너리에 없는 키인 "mykey"를 조회해 보겠습니다.
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("요소 개수 = " + dict.Count);
Console.WriteLine("\n키/값 쌍 출력...");
foreach(KeyValuePair<string, string> res in dict) {
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
if (dict.ContainsKey("mykey"))
Console.WriteLine("키를 찾았습니다!");
else
Console.WriteLine("해당 키는 딕셔너리에 없습니다!");
dict.Clear();
Console.WriteLine("삭제 후 키/값 쌍 출력...");
foreach(KeyValuePair<string, string> res in dict) {
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("현재 요소 개수 = " + dict.Count);
}
}출력 결과
Count of elements = 5 Key/value pairs... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan Key isn't in the dictionary! Cleared Key/value pairs... Count of elements now = 0
"mykey"는 딕셔너리에 등록되어 있지 않으므로 ContainsKey() 메서드가 false를 반환하고, "해당 키는 딕셔너리에 없습니다!"라는 메시지가 출력됩니다.
정리
ContainsKey() 메서드는 딕셔너리에서 키 존재 여부를 빠르게 확인할 수 있는 방법으로, 내부적으로 해시 기반 조회를 사용하기 때문에 평균 O(1)의 시간 복잡도를 가집니다. 존재하지 않는 키에 접근할 때 발생할 수 있는 KeyNotFoundException을 방지하려면, 인덱서로 값을 읽기 전에 반드시 ContainsKey()로 키 존재 여부를 먼저 확인하거나, TryGetValue() 메서드를 사용하는 것이 좋습니다.