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

C# SortedList 객체에 특정 키가 포함되어 있는지 확인하는 방법

C#에서 SortedList 객체에 특정 키가 포함되어 있는지 확인하려면 Contains() 메서드를 사용하면 됩니다. 이 메서드는 지정한 키가 SortedList에 존재하는지 여부를 판단하여 true 또는 false의 불리언(Boolean) 값을 반환합니다.

예제 1

다음은 SortedList에 특정 키가 존재하는지 확인하는 기본적인 예제입니다 −

using System;
using System.Collections;

public class Demo {
   public static void Main() {
      SortedList list = new SortedList();
      list.Add("A", "Books");
      list.Add("B", "Electronics");
      list.Add("C", "Appliances");
      list.Add("D", "Pet Supplies");
      list.Add("E", "Clothing");
      list.Add("F", "Footwear");

      Console.WriteLine("Value associated with key E = " + list["E"]);
      list["E"] = "HDD";
      Console.WriteLine("Value associated with key E [Updated] = " + list["E"]);

      Console.Write("Does the list has key C? = " + list.Contains("C"));
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다 −

Value associated with key E = Clothing
Value associated with key E [Updated] = HDD
Does the list has key C? = True

실행 결과에서 볼 수 있듯이, list.Contains("C")는 키 "C"가 SortedList에 존재하므로 True를 반환했습니다. 또한 인덱서(list["E"])를 사용해 기존 키의 값을 손쉽게 갱신할 수 있다는 점도 확인할 수 있습니다.

예제 2

이번에는 요소 추가, 삭제, 열거자(Enumerator) 순회와 함께 키 존재 여부를 확인하는 좀 더 확장된 예제를 살펴보겠습니다 −

using System;
using System.Collections;

public class Demo {
   public static void Main(String[] args) {
      SortedList sortedList = new SortedList();
      sortedList.Add("A", "1");
      sortedList.Add("B", "2");
      sortedList.Add("C", "3");
      sortedList.Add("D", "4");
      sortedList.Add("E", "5");
      sortedList.Add("F", "6");
      sortedList.Add("G", "7");
      sortedList.Add("H", "8");
      sortedList.Add("I", "9");
      sortedList.Add("J", "10");

      Console.WriteLine("SortedList elements...");
      foreach(DictionaryEntry d in sortedList) {
         Console.WriteLine("Key = " + d.Key + ", Value = " + d.Value);
      }
      Console.WriteLine("Count of SortedList key-value pairs = " + sortedList.Count);

      sortedList.RemoveAt(3);

      Console.WriteLine("\nEnumerator to iterate through the SortedList...");
      IDictionaryEnumerator demoEnum = sortedList.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      Console.WriteLine("Count of SortedList key-value pairs (Updated) = " + sortedList.Count);

      Console.WriteLine("\nDoes the list has key C? = " + sortedList.Contains("C"));
      Console.WriteLine("Does the list has key M? = " + sortedList.Contains("M"));
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다 −

SortedList elements...
Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Key = D, Value = 4
Key = E, Value = 5
Key = F, Value = 6
Key = G, Value = 7
Key = H, Value = 8
Key = I, Value = 9
Key = J, Value = 10
Count of SortedList key-value pairs = 10

Enumerator to iterate through the SortedList...
Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Key = E, Value = 5
Key = F, Value = 6
Key = G, Value = 7
Key = H, Value = 8
Key = I, Value = 9
Key = J, Value = 10
Count of SortedList key-value pairs (Updated) = 9

Does the list has key C? = True
Does the list has key M? = False

결과를 보면 RemoveAt(3)으로 네 번째 요소(키 "D")가 삭제되어 요소 개수가 10개에서 9개로 줄었으며, 존재하는 키 "C"에 대해서는 True, 존재하지 않는 키 "M"에 대해서는 False가 반환된 것을 확인할 수 있습니다.

참고 사항

  • Contains() − 키(Key)의 존재 여부를 확인합니다.
  • ContainsValue() − 값(Value)의 존재 여부를 확인할 때 사용합니다.
  • SortedList는 항상 키를 기준으로 정렬된 상태를 유지하므로, Contains()는 이진 탐색을 통해 O(log n)의 시간 복잡도로 빠르게 동작합니다.
  • 키가 없는 상태에서 인덱서로 값을 읽으면 null이 반환될 수 있으므로, 값을 조회하기 전에 Contains()로 키 존재 여부를 먼저 확인하는 것이 안전합니다.