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

C#에서 OrderedDictionary의 모든 키를 ICollection으로 가져오는 방법

OrderedDictionary는 요소가 삽입된 순서를 유지하는 특수한 컬렉션입니다. 이 컬렉션에 저장된 모든 키를 가져오려면 Keys 속성을 사용하면 되며, 이 속성은 키들을 담고 있는 ICollection 객체를 반환합니다.

반환된 ICollectionCopyTo 메서드를 통해 배열로 복사할 수 있어, 반복문으로 각 키를 손쉽게 출력할 수 있습니다.

예제 1: 숫자 문자열 키 사용하기

다음 예제에서는 OrderedDictionary를 생성하고 여러 개의 키-값 쌍을 추가한 뒤, Keys 속성으로 키 컬렉션을 가져와 배열에 복사하여 화면에 출력합니다.

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.Keys;
      String[] strKeys = new String[dict.Count];
      col.CopyTo(strKeys, 0);

      Console.WriteLine("키 목록 출력...");
      for (int i = 0; i < dict.Count; i++) {
         Console.WriteLine(strKeys[i]);
      }
   }
}

실행 결과

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

키 목록 출력...
1
2
3
4
5
6
7
8

예제 2: 단어 키 사용하기

이번에는 키가 숫자가 아닌 단어 형태인 경우의 예제를 살펴보겠습니다. 동작 방식은 동일하며, 삽입된 순서대로 키가 그대로 유지되는 점을 확인할 수 있습니다.

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

public class Demo {
   public static void Main() {
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("One", "John");
      dict.Add("Two", "Tim");
      dict.Add("Three", "Katie");
      dict.Add("Four", "Andy");
      dict.Add("Five", "Gary");
      dict.Add("Six", "Amy");

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

      Console.WriteLine("키 목록 출력...");
      for (int i = 0; i < dict.Count; i++) {
         Console.WriteLine(strKeys[i]);
      }
   }
}

실행 결과

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

키 목록 출력...
One
Two
Three
Four
Five
Six

핵심 정리

  • dict.Keys 속성은 OrderedDictionary의 모든 키를 포함하는 ICollection을 반환합니다.
  • CopyTo(배열, 시작 인덱스) 메서드를 사용하면 키 컬렉션을 문자열 배열로 복사할 수 있습니다.
  • 배열의 크기는 dict.Count로 지정하여 딕셔너리의 요소 개수와 일치시켜야 합니다.
  • OrderedDictionary는 항목이 추가된 순서를 유지하므로, 키 역시 입력 순서대로 출력됩니다.