C#에서 OrderedDictionary의 모든 요소를 한 번에 제거하려면 Clear() 메서드를 사용하면 됩니다. 이 메서드는 컬렉션에 저장된 모든 키-값 쌍을 삭제하며, 호출 후 Count 속성 값이 0이 됩니다.
C# 코드 예제
다음은 OrderedDictionary에 여러 요소를 추가한 뒤, Clear() 메서드로 전체 요소를 제거하는 예제입니다.
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
동작 방식 설명
- 먼저 6개의 키-값 쌍(A~F)을 OrderedDictionary에 추가합니다.
foreach루프와DictionaryEntry를 사용해 모든 요소를 출력합니다.- 요소 추가 직후
Count값은 6입니다. Clear()메서드 호출 후 모든 요소가 삭제되어Count값이 0으로 변경됩니다.
추가 예제
이번에는 더 간단한 예제로 Clear() 메서드의 동작을 다시 확인해 보겠습니다.
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main(){
OrderedDictionary dict = new OrderedDictionary();
dict.Add("1", "AB");
dict.Add("2", "CD");
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... 1 AB 2 CD Count of elements in OrderedDictionary = 2 Count of elements in OrderedDictionary (Updated)= 0
정리
OrderedDictionary는 삽입 순서를 유지하는 딕셔너리 컬렉션으로, System.Collections.Specialized 네임스페이스에 포함되어 있습니다. 저장된 모든 데이터를 삭제해야 할 때는 요소를 하나씩 제거할 필요 없이 Clear() 메서드 하나만 호출하면 되며, 이후 Count 속성을 통해 컬렉션이 비었는지 손쉽게 확인할 수 있습니다.