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

C# OrderedDictionary 클래스 완벽 정리: 주요 속성과 메서드 활용법

C#의 OrderedDictionary 클래스는 키(key) 또는 인덱스(index)로 접근할 수 있는 키/값 쌍(key/value pair) 컬렉션을 나타냅니다. 일반적인 딕셔너리와 달리 요소가 삽입된 순서를 유지하기 때문에, 순서가 보장되어야 하는 상황에서 매우 유용하게 사용됩니다.

이 클래스는 System.Collections.Specialized 네임스페이스에 포함되어 있으며, 인덱스 기반 접근과 해시 테이블 방식의 빠른 검색이라는 두 가지 장점을 동시에 제공합니다.

OrderedDictionary 클래스의 주요 속성

번호속성 및 설명
1Count
OrderedDictionary 컬렉션에 포함된 키/값 쌍의 개수를 가져옵니다.
2IsReadOnly
OrderedDictionary 컬렉션이 읽기 전용인지 여부를 나타내는 값을 가져옵니다.
3Item[Int32]
지정된 인덱스에 해당하는 값을 가져오거나 설정합니다.
4Item[Object]
지정된 키와 연결된 값을 가져오거나 설정합니다.
5Keys
OrderedDictionary 컬렉션의 모든 키를 포함하는 ICollection 개체를 반환합니다.
6Values
OrderedDictionary 컬렉션의 모든 값을 포함하는 ICollection 개체를 반환합니다.

OrderedDictionary 클래스의 주요 메서드

번호메서드 및 설명
1Add(Object, Object)
지정된 키와 값으로 새 항목을 추가하며, 항목은 사용 가능한 가장 낮은 인덱스 위치에 저장됩니다.
2AsReadOnly()
현재 OrderedDictionary 컬렉션의 읽기 전용 복사본을 반환합니다.
3Clear()
OrderedDictionary 컬렉션에서 모든 요소를 제거합니다.
4Contains(Object)
OrderedDictionary 컬렉션에 특정 키가 포함되어 있는지 확인합니다.
5CopyTo(Array, Int32)
OrderedDictionary의 요소를 지정된 인덱스 위치에서 시작하여 1차원 Array 개체에 복사합니다.
6Equals(Object)
지정된 개체가 현재 개체와 같은지 여부를 확인합니다. (Object 클래스에서 상속)
7GetEnumerator()
OrderedDictionary 컬렉션을 반복(iterate)할 수 있는 IDictionaryEnumerator 개체를 반환합니다.

예제 1: Count 속성으로 요소 개수 확인하기

다음 예제는 OrderedDictionary에 포함된 키/값 쌍의 개수를 구하는 코드입니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
    public static void Main() {
        OrderedDictionary dict = new OrderedDictionary();
        dict.Add("A", "Home Appliances");
        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 elements...");
        foreach(DictionaryEntry d in dict) {
            Console.WriteLine(d.Key + " " + d.Value);
        }
        Console.WriteLine("Count of elements in OrderedDictionary = " + dict.Count);
        dict.Clear();
        Console.WriteLine("Count of elements in OrderedDictionary (Updated)= " + dict.Count);
    }
}

실행 결과

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

OrderedDictionary elements...
A Home Appliances
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
Count of elements in OrderedDictionary = 6
Count of elements in OrderedDictionary (Updated)= 0

위 예제에서는 먼저 6개의 항목을 추가한 후 Count 속성으로 전체 요소 수(6)를 출력했습니다. 이후 Clear() 메서드를 호출해 모든 요소를 제거하면 개수가 0으로 갱신되는 것을 확인할 수 있습니다.

예제 2: Clear() 메서드로 모든 요소 제거하기

다음 예제는 Clear() 메서드를 사용해 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 elements...");
        foreach(DictionaryEntry d in dict) {
            Console.WriteLine(d.Key + " " + d.Value);
        }
        Console.WriteLine("Count of elements in OrderedDictionary = " + dict.Count);
        dict.Clear();
        Console.WriteLine("Count of elements in OrderedDictionary (Updated)= " + dict.Count);
    }
}

실행 결과

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

OrderedDictionary elements...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
Count of elements in OrderedDictionary = 6
Count of elements in OrderedDictionary (Updated)= 0

정리

OrderedDictionary는 키 기반 조회와 삽입 순서 유지라는 두 가지 특징을 모두 갖춘 컬렉션입니다. Add(), Clear(), Contains() 등의 메서드와 Count, Keys, Values 같은 속성을 활용하면 데이터를 직관적이고 안전하게 관리할 수 있습니다. 특히 요소의 입력 순서가 중요한 시나리오에서 Hashtable 대신 OrderedDictionary를 사용하는 것이 좋은 선택입니다.