Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# Dictionary.ContainsValue() 메서드 완벽 정리 – 특정 값 존재 여부 확인하기

Dictionary.ContainsValue() 메서드란?

C#에서 Dictionary<TKey,TValue> 컬렉션은 키(Key)와 값(Value) 쌍으로 데이터를 저장하는 대표적인 자료구조입니다. 이때 ContainsValue() 메서드를 사용하면 딕셔너리에 특정 값이 존재하는지 여부를 손쉽게 확인할 수 있습니다.

이 메서드는 지정한 값이 딕셔너리에 존재하면 true, 존재하지 않으면 false를 반환합니다.

구문(Syntax)

public bool ContainsValue (TValue val);

매개변수 val은 딕셔너리에서 검색하고자 하는 값입니다.

예제 1 – 값이 존재하는 경우

다음 예제는 Dictionary.ContainsValue() 메서드를 활용하여 특정 값("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")으로 ContainsValue() 메서드를 호출해 보겠습니다.

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

정리

Dictionary.ContainsValue() 메서드는 값 기반 검색 시 유용하지만, 내부적으로 모든 요소를 순회하기 때문에 시간 복잡도가 O(n)입니다. 반면 키 기반 조회인 ContainsKey()는 해시 기반으로 동작하여 O(1)에 가까운 성능을 보입니다. 따라서 빈번한 검색이 필요하다면 가능한 한 키를 활용하는 것이 좋습니다.