C#의 OrderedDictionary는 키와 값의 쌍을 저장하면서 각 항목이 삽입된 순서를 그대로 유지하는 컬렉션입니다. 일반적인 해시테이블 기반 컬렉션과 달리 요소를 순회하면 입력 순서대로 반환되므로, 순서가 중요한 데이터를 다룰 때 매우 유용합니다. OrderedDictionary에 키와 값을 추가하려면 Add() 메서드를 사용하면 됩니다.
예제 1: 키와 값 추가 후 컬렉션 비교하기
다음 예제에서는 두 개의 OrderedDictionary 객체를 생성하고 각각 여러 개의 키-값 쌍을 추가합니다. 이후 foreach 문으로 모든 요소를 출력한 뒤, Equals() 메서드를 사용해 두 컬렉션이 동일한지 확인합니다.
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
OrderedDictionary dict1 = new OrderedDictionary();
dict1.Add("A", "Books");
dict1.Add("B", "Electronics");
dict1.Add("C", "Smart Wearables");
dict1.Add("D", "Pet Supplies");
dict1.Add("E", "Clothing");
dict1.Add("F", "Footwear");
Console.WriteLine("OrderedDictionary1 elements...");
foreach(DictionaryEntry d in dict1) {
Console.WriteLine(d.Key + " " + d.Value);
}
OrderedDictionary dict2 = new OrderedDictionary();
dict2.Add("1", "One");
dict2.Add("2", "Two");
dict2.Add("3", "Three");
dict2.Add("4", "Four");
dict2.Add("5", "Five");
dict2.Add("6", "Six");
Console.WriteLine("\nOrderedDictionary2 elements...");
foreach(DictionaryEntry d in dict2) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("\nIs OrderedDictionary1 equal to OrderedDictionary2? = " + (dict1.Equals(dict2)));
}
}
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
OrderedDictionary1 elements... A Books B Electronics C Smart Wearables D Pet Supplies E Clothing F Footwear OrderedDictionary2 elements... 1 One 2 Two 3 Three 4 Four 5 Five 6 Six Is OrderedDictionary1 equal to OrderedDictionary2? = False
코드 설명
dict1에는 A부터 F까지의 문자열 키와 카테고리 이름이 값으로 저장되고, dict2에는 숫자 키와 해당 영어 단어가 저장됩니다. 두 컬렉션은 형태는 비슷하지만 실제 내용이 다르기 때문에 Equals() 비교 결과는 False가 반환됩니다. 또한 출력 결과에서 확인할 수 있듯이, 모든 요소는 추가된 순서 그대로 유지됩니다.
예제 2: 값 가져오기와 키 존재 여부 확인
두 번째 예제에서는 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("Displaying the values...");
for (int i = 0; i < dict.Count; i++) {
Console.WriteLine(strVal[i]);
}
Console.WriteLine("Is OrderedDictionary read-only? = " + dict.IsReadOnly);
Console.WriteLine("The OrderedDictionary has the key 15? = " + dict.Contains("15"));
Console.WriteLine("The OrderedDictionary has the key 5? = " + dict.Contains("5"));
}
}
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Displaying the values... One Two Three Four Five Six Seven Eight Is OrderedDictionary read-only? = False The OrderedDictionary has the key 15? = False The OrderedDictionary has the key 5? = True
코드 설명
Values 속성은 컬렉션에 저장된 모든 값을 담고 있는 ICollection을 반환하며, CopyTo() 메서드를 사용하면 이 값들을 String 배열로 손쉽게 복사할 수 있습니다. IsReadOnly 속성은 컬렉션이 읽기 전용인지 여부를 나타내며, 이 예제에서는 False이므로 항목 추가와 수정이 자유롭습니다. 마지막으로 Contains() 메서드는 지정한 키의 존재 여부를 bool 값으로 반환합니다. 키 "15"는 존재하지 않으므로 False, 키 "5"는 존재하므로 True가 출력됩니다.