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

C# SortedDictionary.ContainsValue() 메서드 사용법과 예제

C#의 SortedDictionary.ContainsValue() 메서드는 SortedDictionary<TKey, TValue> 컬렉션 안에 지정한 값과 일치하는 요소가 존재하는지 확인할 때 사용합니다. 해당 값이 존재하면 true, 존재하지 않으면 false를 반환합니다.

구문

public bool ContainsValue(TValue val);

매개변수 val은 SortedDictionary<TKey, TValue>에서 검색하려는 값입니다. 이 메서드는 키가 아닌 값(value)을 대상으로 검색한다는 점에 유의하세요.

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

다음 예제에서는 노트북 관련 제품 정보를 SortedDictionary에 저장한 뒤, ContainsValue() 메서드로 특정 값("Notebook")이 있는지 확인합니다.

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
      sortedDict.Add(100, "Inspiron");
      sortedDict.Add(200, "Alienware");
      sortedDict.Add(300, "Projectors");
      sortedDict.Add(400, "XPS");

      Console.WriteLine("SortedDictionary 키-값 쌍 목록...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("키 = " + demoEnum.Key + ", 값 = " + demoEnum.Value);
      Console.WriteLine("키-값 쌍 개수 = " + sortedDict.Count);

      sortedDict.Add(800, "Notebook");
      sortedDict.Add(10000, "Bluetooth Speaker");

      Console.WriteLine("\nSortedDictionary 키-값 쌍 목록...(업데이트)");
      demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("키 = " + demoEnum.Key + ", 값 = " + demoEnum.Value);
      Console.WriteLine("키-값 쌍 개수(업데이트) = " + sortedDict.Count);

      Console.WriteLine("값이 SortedDictionary에 존재하는가? = " + sortedDict.ContainsValue("Notebook"));

      sortedDict.Clear();
      Console.WriteLine("\n키-값 쌍 개수(Clear 후) = " + sortedDict.Count);
   }
}

실행 결과

SortedDictionary 키-값 쌍 목록...
키 = 100, 값 = Inspiron
키 = 200, 값 = Alienware
키 = 300, 값 = Projectors
키 = 400, 값 = XPS
키-값 쌍 개수 = 4
SortedDictionary 키-값 쌍 목록...(업데이트)
키 = 100, 값 = Inspiron
키 = 200, 값 = Alienware
키 = 300, 값 = Projectors
키 = 400, 값 = XPS
키 = 800, 값 = Notebook
키 = 10000, 값 = Bluetooth Speaker
키-값 쌍 개수(업데이트) = 6
값이 SortedDictionary에 존재하는가? = True
키-값 쌍 개수(Clear 후) = 0

실행 결과를 보면 "Notebook"이라는 값이 컬렉션에 존재하기 때문에 ContainsValue() 메서드가 True를 반환한 것을 확인할 수 있습니다. 마지막에는 Clear() 메서드로 모든 요소를 제거하여 개수가 0이 된 것도 볼 수 있습니다.

예제 2: 값이 존재하지 않는 경우

이번에는 검색하려는 값이 컬렉션에 없을 때 어떻게 동작하는지 살펴보겠습니다.

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
      sortedDict.Add(1, "One");
      sortedDict.Add(2, "Two");
      sortedDict.Add(3, "Three");
      sortedDict.Add(4, "Four");
      sortedDict.Add(5, "Five");
      sortedDict.Add(6, "Six");

      Console.WriteLine("SortedDictionary 키-값 쌍 목록...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("키 = " + demoEnum.Key + ", 값 = " + demoEnum.Value);
      Console.WriteLine("키-값 쌍 개수 = " + sortedDict.Count);

      sortedDict.Add(7, "Seven");
      sortedDict.Add(8, "Eight");

      Console.WriteLine("\nSortedDictionary 키-값 쌍 목록...(업데이트)");
      demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("키 = " + demoEnum.Key + ", 값 = " + demoEnum.Value);
      Console.WriteLine("키-값 쌍 개수(업데이트) = " + sortedDict.Count);

      Console.WriteLine("값이 SortedDictionary에 존재하는가? = " + sortedDict.ContainsValue("Eleven"));

      sortedDict.Clear();
      Console.WriteLine("\n키-값 쌍 개수(Clear 후) = " + sortedDict.Count);
   }
}

실행 결과

SortedDictionary 키-값 쌍 목록...
키 = 1, 값 = One
키 = 2, 값 = Two
키 = 3, 값 = Three
키 = 4, 값 = Four
키 = 5, 값 = Five
키 = 6, 값 = Six
키-값 쌍 개수 = 6
SortedDictionary 키-값 쌍 목록...(업데이트)
키 = 1, 값 = One
키 = 2, 값 = Two
키 = 3, 값 = Three
키 = 4, 값 = Four
키 = 5, 값 = Five
키 = 6, 값 = Six
키 = 7, 값 = Seven
키 = 8, 값 = Eight
키-값 쌍 개수(업데이트) = 8
값이 SortedDictionary에 존재하는가? = False
키-값 쌍 개수(Clear 후) = 0

컬렉션에 "Eleven"이라는 값이 없기 때문에 이번에는 False가 반환되었습니다.

참고 사항

  • 성능: ContainsValue()는 내부적으로 모든 요소를 순회하는 선형 검색(O(n))을 수행합니다. 반면 ContainsKey()는 정렬된 트리 구조 덕분에 O(log n)으로 훨씬 빠르므로, 키 검색이 가능하다면 ContainsKey()를 사용하는 것이 좋습니다.
  • 값 비교 방식: 값의 동일 여부는 기본적으로 EqualityComparer<TValue>.Default를 통해 비교됩니다.
  • 대소문자 구분: 문자열 값의 경우 기본 비교자가 대소문자를 구분하므로 "notebook"과 "Notebook"은 서로 다른 값으로 취급됩니다.