C#의 Dictionary<TKey, TValue>.Clear() 메서드는 딕셔너리에 저장된 모든 키/값 쌍(key-value pair)을 한 번에 제거합니다. 이 메서드를 호출하면 Count 속성 값이 0이 되며, 딕셔너리는 완전히 비어 있는 상태로 초기화됩니다.
문법(Syntax)
public void Clear();
Clear() 메서드는 매개변수도 반환값도 없습니다. 단순히 딕셔너리 내부의 모든 요소를 삭제하는 역할만 수행하며, 호출 즉시 모든 키와 값이 사라집니다.
예제 1
다음은 Dictionary.Clear() 메서드의 기본적인 사용법을 보여주는 예제입니다.
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict =
new Dictionary<string, string>();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("Count of elements = "+dict.Count);
Console.WriteLine("\nKey/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
dict.Clear();
Console.WriteLine("Cleared Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("Count of elements now = "+dict.Count);
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Count of elements = 5 Key/value pairs... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan Cleared Key/value pairs... Count of elements now = 0
실행 결과를 살펴보면, Clear() 메서드 호출 이후 foreach 루프에서 더 이상 어떤 항목도 출력되지 않았으며, 요소 개수(Count)가 5에서 0으로 변경된 것을 확인할 수 있습니다.
예제 2
이번에는 기존 요소에 새로운 항목을 추가한 뒤, Clear() 메서드로 전체를 삭제하는 또 다른 예제입니다.
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict =
new Dictionary<string, string>();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("Count of elements = "+dict.Count);
dict.Add("Six", "Anne");
dict.Add("Seven", "Katoe");
Console.WriteLine("Count of elements (updated) = "+dict.Count);
Console.WriteLine("Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
dict.Clear();
Console.WriteLine("Cleared Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Count of elements = 5 Count of elements (updated) = 7 Key/value pairs... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan Key = Six, Value = Anne Key = Seven, Value = Katoe Cleared Key/value pairs...
정리
Dictionary.Clear() 메서드는 반복문 없이 딕셔너리의 모든 데이터를 손쉽게 비울 수 있는 간편하고 효율적인 방법입니다. 참고로 Clear()는 저장된 요소만 제거할 뿐, 딕셔너리 객체 자체나 내부 용량(capacity)까지 삭제하지는 않으므로, 이후 같은 딕셔너리에 계속해서 새로운 데이터를 추가할 수 있습니다.