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

C# OrderedDictionary 컬렉션에서 특정 키 존재 여부 확인하는 방법

C#의 OrderedDictionary(System.Collections.Specialized 네임스페이스)는 키와 값을 한 쌍으로 저장하며, 요소가 추가된 순서를 그대로 유지하는 특수한 컬렉션입니다. 일반 Dictionary와 달리 인덱스 또는 키를 모두 사용해 요소에 접근할 수 있다는 장점이 있습니다.

이 컬렉션에 특정 키가 포함되어 있는지 확인하려면 Contains() 메서드를 사용합니다. 이 메서드는 지정한 키가 존재하면 true, 존재하지 않으면 false를 반환합니다. 단, 매개변수로 null을 전달하면 ArgumentNullException이 발생하므로 주의해야 합니다.

예제 1: 숫자 키 존재 여부 확인

다음 예제에서는 문자열 형태의 숫자 키를 가진 OrderedDictionary를 생성한 뒤, Contains() 메서드로 키의 존재 여부를 확인합니다.

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
   public static void Main(){
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("1", "One");
      dict.Add("2", "Two");
      dict.Add("3", "Three");
      dict.Add("4", "Four");
      dict.Add("5", "Five");
      dict.Add("6", "Six");
      dict.Add("7", "Seven");
      dict.Add("8", "Eight");

      ICollection col = dict.Values;
      String[] strVal = new String[dict.Count];
      col.CopyTo(strVal, 0);

      Console.WriteLine("저장된 값 출력...");
      for (int i = 0; i < dict.Count; i++) {
         Console.WriteLine(strVal[i]);
      }

      Console.WriteLine("OrderedDictionary가 읽기 전용인가요? = " + dict.IsReadOnly);
      Console.WriteLine("OrderedDictionary에 키 15가 있나요? = " + dict.Contains("15"));
      Console.WriteLine("OrderedDictionary에 키 5가 있나요? = " + dict.Contains("5"));
   }
}

실행 결과

저장된 값 출력...
One
Two
Three
Four
Five
Six
Seven
Eight
OrderedDictionary가 읽기 전용인가요? = False
OrderedDictionary에 키 15가 있나요? = False
OrderedDictionary에 키 5가 있나요? = True

결과 해석

키 "15"는 사전에 추가된 적이 없으므로 false가 반환되었고, 키 "5"는 실제로 존재하므로 true가 반환되었습니다. 또한 IsReadOnly 속성이 False를 반환하므로, 이 컬렉션은 읽기 전용이 아니며 요소를 자유롭게 추가·수정·삭제할 수 있습니다.

예제 2: 문자 키 존재 여부 확인

이번에는 A부터 J까지의 문자 키를 사용한 두 번째 예제입니다.

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
   public static void Main(){
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("A", "Pen");
      dict.Add("B", "Pencil");
      dict.Add("C", "Notebook");
      dict.Add("D", "Table");
      dict.Add("E", "Chair");
      dict.Add("F", "Coworking");
      dict.Add("G", "Cubicle");
      dict.Add("H", "Sticky Notes");
      dict.Add("I", "WhiteBoard");
      dict.Add("J", "Marker");

      ICollection col = dict.Values;
      String[] strVal = new String[dict.Count];
      col.CopyTo(strVal, 0);

      Console.WriteLine("저장된 값 출력...");
      for (int i = 0; i < dict.Count; i++) {
         Console.WriteLine(strVal[i]);
      }

      Console.WriteLine("OrderedDictionary가 읽기 전용인가요? = " + dict.IsReadOnly);
      Console.WriteLine("OrderedDictionary에 키 B가 있나요? = " + dict.Contains("B"));
   }
}

실행 결과

저장된 값 출력...
Pen
Pencil
Notebook
Table
Chair
Coworking
Cubicle
Sticky Notes
WhiteBoard
Marker
OrderedDictionary가 읽기 전용인가요? = False
OrderedDictionary에 키 B가 있나요? = True

핵심 정리

  • Contains(key): 키의 존재 여부를 bool 값으로 반환합니다.
  • IsReadOnly: 컬렉션이 읽기 전용인지 여부를 나타냅니다.
  • Contains()에 null을 전달하면 ArgumentNullException이 발생합니다.
  • OrderedDictionary는 값(value) 존재 여부를 확인하는 전용 메서드를 제공하지 않으므로, Values 컬렉션을 순회하거나 CopyTo()로 배열에 복사한 후 직접 비교해야 합니다.