C#에서 Dictionary<TKey, TValue> 컬렉션에 특정 값이 존재하는지 확인하려면 ContainsValue() 메서드를 사용합니다. 이 메서드는 지정한 값이 딕셔너리의 값(Value) 목록 중 하나와 일치하면 true를, 그렇지 않으면 false를 반환합니다.
참고로 키(Key)의 존재 여부를 확인할 때는 ContainsKey() 메서드를 사용하며, 이 경우 해시 기반 조회로 O(1)의 성능을 보이지만, ContainsValue()는 모든 값을 순회해야 하므로 O(n)의 시간 복잡도를 가집니다.
예제 1: 값이 존재하는 경우
다음 예제에서는 문자열 키와 값을 가지는 딕셔너리를 생성하고, "Kevin"이라는 값이 포함되어 있는지 확인합니다.
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.ContainsValue("Kevin"))
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);
}
}출력 결과
요소 개수 = 5 키/값 쌍 출력... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan 값을 찾았습니다! 초기화된 키/값 쌍... 현재 요소 개수 = 0
예제 2: 값이 존재하지 않는 경우
이번에는 딕셔너리에 존재하지 않는 값 "Angelina"로 검색했을 때의 동작을 살펴보겠습니다.
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "Chris");
dict.Add("Two", "Steve");
dict.Add("Three", "Messi");
dict.Add("Four", "Ryan");
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.ContainsValue("Angelina"))
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);
}
}출력 결과
요소 개수 = 5 키/값 쌍 출력... Key = One, Value = Chris Key = Two, Value = Steve Key = Three, Value = Messi Key = Four, Value = Ryan Key = Five, Value = Nathan 딕셔너리에 해당 값이 없습니다! 초기화된 키/값 쌍... 현재 요소 개수 = 0
정리
ContainsValue(TValue value): 딕셔너리에 특정 값이 있는지 확인하며, 기본 비교자(EqualityComparer<TValue>.Default)를 사용하여 비교합니다.- 값 검색은 선형 탐색 방식으로 수행되므로, 대용량 데이터에서 빈번하게 호출한다면 성능에 유의해야 합니다.
Clear()메서드를 호출하면 딕셔너리의 모든 키/값 쌍이 제거되어 요소 개수가 0이 됩니다.