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

C# StringDictionary에서 키(Key) 컬렉션 가져오는 방법

C#의 StringDictionary에서 저장된 모든 키(key)의 컬렉션을 가져오려면 Keys 속성을 사용합니다. Keys 속성은 컬렉션에 포함된 키들을 ICollection 형태로 반환하며, 이를 CopyTo 메서드로 문자열 배열에 복사하면 인덱스를 통해 개별 키에 손쉽게 접근할 수 있습니다.

예제 1

다음은 두 개의 StringDictionary를 생성하고, Keys 속성을 활용해 키 컬렉션을 배열로 가져오는 예제입니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      StringDictionary strDict1 = new StringDictionary();
      strDict1.Add("U", "Electronics");
      strDict1.Add("V", "Toys");
      strDict1.Add("W", "Books");
      strDict1.Add("X", "Accessories");
      Console.WriteLine("StringDictionary1 elements...");
      foreach(DictionaryEntry d in strDict1){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("Does StringDictionary1 has key G? "+strDict1.ContainsKey("G"));
      StringDictionary strDict2 = new StringDictionary();
      strDict2.Add("A", "John");
      strDict2.Add("B", "Andy");
      strDict2.Add("C", "Tim");
      strDict2.Add("D", "Ryan");
      strDict2.Add("E", "Kevin");
      strDict2.Add("F", "Katie");
      strDict2.Add("G", "Brad");
      Console.WriteLine("\nStringDictionary2 elements...");
      foreach(DictionaryEntry d in strDict2){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("\nCollection of keys (StringDictionary2)...");
      String[] keyArr = new String[strDict2.Count];
      strDict2.Keys.CopyTo(keyArr, 0);
      for (int i = 0; i < strDict2.Count; i++) {
         Console.WriteLine("Key "+(i+1)+" = "+keyArr[i]);
      }
      Console.WriteLine("\nIs Dictionary2 equal to Dictionary1? = "+strDict2.Equals(strDict1));
      Console.WriteLine("Does StringDictionary2 has key B? "+strDict2.ContainsKey("B"));
   }
}

출력 결과

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

StringDictionary1 elements...
x Accessories
u Electronics
v Toys
w Books
Does StringDictionary1 has key G? False StringDictionary2 elements...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad
Collection of keys (StringDictionary2)...
Key 1 = a
Key 2 = b
Key 3 = c
Key 4 = d
Key 5 = e
Key 6 = f
Key 7 = g
Is Dictionary2 equal to Dictionary1? = False
Does StringDictionary2 has key B? True

예제 2

이번에는 키뿐만 아니라 각 키에 해당하는 값(value)까지 함께 출력하는 예제를 살펴보겠습니다. 복사한 키 배열을 인덱서에 전달하면 해당 키의 값을 조회할 수 있습니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      StringDictionary strDict1 = new StringDictionary();
      strDict1.Add("S", "Home Appliances");
      strDict1.Add("T", "Smart Wearable Tech");
      strDict1.Add("U", "Electronics");
      strDict1.Add("V", "Toys");
      strDict1.Add("W", "Books");
      strDict1.Add("X", "Accessories");
      Console.WriteLine("StringDictionary elements...");
      foreach(DictionaryEntry d in strDict1){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("\nCollection of keys and values...");
      String[] keyArr = new String[strDict1.Count];
      strDict1.Keys.CopyTo(keyArr, 0);
      for (int i = 0; i < strDict1.Count; i++) {
         Console.WriteLine("Key "+(i+1)+" = "+keyArr[i]+", Value "+(i+1)+" = "+strDict1[keyArr[i]]);
      }
      Console.WriteLine("\nDoes StringDictionary has key B? "+strDict1.ContainsKey("B"));
   }
}

출력 결과

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

StringDictionary elements...
x Accessories
s Home Appliances
t Smart Wearable Tech
u Electronics
v Toys
w Books
Collection of keys and values...
Key 1 = x, Value 1 = Accessories
Key 2 = s, Value 2 = Home Appliances
Key 3 = t, Value 3 = Smart Wearable Tech
Key 4 = u, Value 4 = Electronics
Key 5 = v, Value 5 = Toys
Key 6 = w, Value 6 = Books
Does StringDictionary has key B? False

핵심 정리

  • Keys 속성: StringDictionary에 저장된 모든 키를 ICollection 형태로 반환합니다.
  • CopyTo 메서드: 반환된 키 컬렉션을 지정한 시작 인덱스(위 예제에서는 0)부터 문자열 배열로 복사합니다.
  • ContainsKey 메서드: 특정 키가 사전에 존재하는지 확인하여 true 또는 false를 반환합니다.
  • StringDictionary는 내부적으로 키를 소문자로 변환하여 처리하기 때문에, 대문자로 입력한 키도 출력 결과에서는 소문자로 표시됩니다.