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

C#에서 OrderedDictionary 생성하고 활용하는 방법

C#에서 OrderedDictionary는 키-값 쌍을 저장하면서도 요소가 추가된 순서를 그대로 유지하는 컬렉션입니다. 일반 Hashtable이나 Dictionary와 달리 삽입 순서가 보존되므로 순서가 중요한 데이터를 처리할 때 매우 유용합니다. OrderedDictionary는 System.Collections.Specialized 네임스페이스에 포함되어 있으며, 각 요소는 DictionaryEntry 객체로 접근할 수 있습니다.

예제 1: OrderedDictionary 생성 및 요소 관리

다음은 OrderedDictionary를 생성하고 요소를 추가한 뒤, 특정 요소를 제거하는 예제입니다.

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

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

      Console.WriteLine("OrderedDictionary 요소...");
      foreach(DictionaryEntry d in dict) {
         Console.WriteLine(d.Key + " " + d.Value);
      }

      Console.WriteLine("OrderedDictionary의 요소 개수 = " + dict.Count);

      dict.Remove("E");
      Console.WriteLine("OrderedDictionary의 요소 개수(업데이트 후) = " + dict.Count);
   }
}

출력 결과

OrderedDictionary 요소...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
OrderedDictionary의 요소 개수 = 6
OrderedDictionary의 요소 개수(업데이트 후) = 5

Add() 메서드로 키와 값을 순서대로 추가했으며, foreach 문과 DictionaryEntry를 사용해 모든 요소를 순회했습니다. Count 속성으로 현재 요소 개수를 확인할 수 있고, Remove() 메서드에 키 "E"를 전달해 해당 요소를 제거하자 개수가 6에서 5로 줄어든 것을 확인할 수 있습니다.

예제 2: OrderedDictionary에서 키 목록 가져오기

이번에는 Keys 속성과 CopyTo() 메서드를 활용해 OrderedDictionary의 모든 키를 배열로 추출하는 방법을 살펴보겠습니다.

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

Keys 속성은 컬렉션의 모든 키를 ICollection 형태로 반환합니다. 이를 CopyTo() 메서드로 문자열 배열에 복사한 후 반복문을 통해 삽입된 순서대로 키를 출력할 수 있습니다.

정리

OrderedDictionary는 삽입 순서를 보장하는 키-값 컬렉션이 필요할 때 유용한 선택지입니다. 키는 중복될 수 없으며, 인덱스 기반 접근도 함께 지원하므로 순서가 중요한 데이터 구조를 구현할 때 적극적으로 활용해 보시기 바랍니다.