C#의 Dictionary<TKey, TValue>.ContainsKey() 메서드는 딕셔너리에 특정 키가 존재하는지 여부를 확인하는 데 사용됩니다. 지정한 키가 딕셔너리 안에 있으면 true를 반환하고, 없으면 false를 반환합니다.
문법(Syntax)
public bool ContainsKey (TKey key);
위 문법에서 매개변수 key는 딕셔너리에서 찾고자 하는 키를 의미합니다.
주요 특징
- 키가 존재하면
true, 존재하지 않으면false를 반환합니다. - 존재하지 않는 키에 접근할 때 발생하는
KeyNotFoundException을 사전에 방지할 수 있습니다. - 해시 기반 조회 방식을 사용하므로 검색 속도가 매우 빠릅니다(평균 O(1)).
예제 1: 존재하는 키 확인하기
다음은 Dictionary.ContainsKey() 메서드를 구현하는 첫 번째 예제입니다.
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("Count of elements = "+dict.Count);
Console.WriteLine("
Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
if (dict.ContainsKey("Three"))
Console.WriteLine("Key found!");
else
Console.WriteLine("Key isn't in the dictionary!");
dict.Clear();
Console.WriteLine("Cleared Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("Count of elements now = "+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()로 확인했기 때문에 "Key found!"가 출력되었습니다. 이후 Clear() 메서드로 모든 요소를 제거하면 요소 개수가 0으로 변경되는 것을 확인할 수 있습니다.
예제 2: 존재하지 않는 키 확인하기
이번에는 딕셔너리에 존재하지 않는 키를 조회하는 경우를 살펴보겠습니다.
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("Count of elements = "+dict.Count);
Console.WriteLine("
Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
if (dict.ContainsKey("mykey"))
Console.WriteLine("Key found!");
else
Console.WriteLine("Key isn't in the dictionary!");
dict.Clear();
Console.WriteLine("Cleared Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("Count of elements now = "+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"를 조회했으므로 "Key isn't in the dictionary!"라는 메시지가 출력됩니다.
마무리 정리
Dictionary.ContainsKey() 메서드는 C#에서 딕셔너리의 키 존재 여부를 안전하게 확인할 수 있는 필수적인 메서드입니다. 인덱서(dict[key])로 직접 값에 접근하기 전에 이 메서드로 키의 존재 여부를 먼저 검사하면 런타임 예외를 효과적으로 예방할 수 있습니다. 또한 TryGetValue()와 함께 활용하면 더욱 안전하고 효율적인 딕셔너리 처리 코드를 작성할 수 있습니다.