C# ListDictionary에서 모든 항목 제거하기
C#의 ListDictionary는 키(key)와 값(value)으로 구성된 항목을 저장하는 특수 컬렉션 클래스입니다. 이 컬렉션에 담긴 모든 키/값 쌍을 한 번에 삭제하려면 Clear() 메서드를 사용하면 됩니다. Clear() 메서드를 호출하면 컬렉션의 모든 요소가 제거되고, Count 속성 값도 0으로 변경됩니다.
그럼 실제 코드 예제를 통해 동작 방식을 자세히 살펴보겠습니다.
예제 1: ListDictionary의 모든 항목 삭제
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main(){
ListDictionary dict1 = new ListDictionary();
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("ListDictionary1 elements...");
foreach(DictionaryEntry d in dict1){
Console.WriteLine(d.Key + " " + d.Value);
}
ListDictionary dict2 = new ListDictionary();
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("\nListDictionary2 elements...");
foreach(DictionaryEntry d in dict2){
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("Count of key/value pairs in Dictionary 2 = "+dict2.Count);
ListDictionary dict3 = new ListDictionary();
dict3 = dict2;
Console.WriteLine("\nIs ListDictionary3 equal to ListDictionary2? = "+(dict3.Equals(dict2)));
dict3.Clear();
Console.WriteLine("Count of key/value pairs in Dictionary 3 = "+dict3.Count);
}
}
출력 결과
위 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.
ListDictionary1 elements... A Books B Electronics C Smart Wearables D Pet Supplies E Clothing F Footwear ListDictionary2 elements... 1 One 2 Two 3 Three 4 Four 5 Five 6 Six Count of key/value pairs in Dictionary 2 = 6 Is ListDictionary3 equal to ListDictionary2? = True Count of key/value pairs in Dictionary 3 = 0
여기서 주목해야 할 부분은 dict3 = dict2; 구문입니다. 이 코드는 새로운 객체를 생성하는 것이 아니라 dict2와 동일한 객체를 함께 참조하도록 만듭니다. 따라서 dict3.Clear()를 호출하면 사실상 dict2의 내용까지 함께 비워지며, Equals() 메서드가 True를 반환한 것도 두 변수가 같은 객체를 가리키고 있기 때문입니다.
예제 2: Count 속성으로 항목 개수 확인하기
이번에는 Clear()를 호출하지 않고, ListDictionary에 저장된 항목 개수를 Count 속성으로 확인하는 간단한 예제입니다.
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main(){
ListDictionary dict1 = new ListDictionary();
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("ListDictionary1 elements...");
foreach(DictionaryEntry d in dict1){
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("Count of key/value pairs in Dictionary 1 = "+dict1.Count);
}
}
출력 결과
ListDictionary1 elements... A Books B Electronics C Smart Wearables D Pet Supplies E Clothing F Footwear Count of key/value pairs in Dictionary 1 = 6
핵심 정리
- Clear() – ListDictionary의 모든 키/값 쌍을 한 번에 제거합니다.
- Count – 현재 저장된 키/값 쌍의 개수를 반환합니다.
- 참조 공유 주의 – dict3 = dict2처럼 대입하면 두 변수가 같은 객체를 참조하므로, 한쪽을 Clear()하면 다른 쪽 내용도 함께 사라집니다.