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

C# SortedDictionary.Clear() 메서드 완벽 정리 – 모든 요소 제거하기

C#의 SortedDictionary.Clear() 메서드는 SortedDictionary<TKey, TValue> 컬렉션에 저장된 모든 키-값 쌍을 한 번에 제거하는 데 사용됩니다. 이 메서드를 호출하면 컬렉션의 Count 속성이 0이 되지만, 컬렉션 객체 자체는 그대로 유지되므로 이후에 새로운 요소를 계속 추가할 수 있습니다.

구문

Clear() 메서드의 기본 구문은 다음과 같습니다.

public void Clear ();

주요 특징

  • 매개변수를 받지 않고 반환값도 없습니다(void).
  • 호출 후 Count 속성은 항상 0이 됩니다.
  • 기존에 있던 키는 더 이상 ContainsKey()로 조회되지 않습니다.

예제 1

다음은 Clear() 메서드의 기본적인 사용 예입니다.

using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
      sortedDict.Add(100, "Mobile");
      sortedDict.Add(200, "Laptop");
      sortedDict.Add(300, "Desktop");
      sortedDict.Add(400, "Speakers");
      sortedDict.Add(500, "Headphone");
      sortedDict.Add(600, "Earphone");
      Console.WriteLine("SortedDictionary key-value pairs...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
      Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      Console.WriteLine("Count of SortedDictionary key-value pairs = "+sortedDict.Count);
      Console.WriteLine("\nThe SortedDictionary has the key 200? = "+sortedDict.ContainsKey(200));
      sortedDict.Clear();
      Console.WriteLine("Count of SortedDictionary key-value pairs = "+sortedDict.Count);
   }
}

실행 결과

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

SortedDictionary key-value pairs...
Key = 100, Value = Mobile
Key = 200, Value = Laptop
Key = 300, Value = Desktop
Key = 400, Value = Speakers
Key = 500, Value = Headphone
Key = 600, Value = Earphone
Count of SortedDictionary key-value pairs = 6
The SortedDictionary has the key 200? = True
Count of SortedDictionary key-value pairs = 0

출력 결과를 보면 Clear() 호출 전에는 6개의 키-값 쌍이 존재했고, 키 200에 대한 ContainsKey() 확인도 True를 반환했습니다. 하지만 Clear() 호출 후에는 Count가 0으로 변경된 것을 확인할 수 있습니다.

예제 2

이번에는 요소를 추가한 뒤 Clear()로 전체를 비우는 과정을 단계별로 살펴보겠습니다.

using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
      sortedDict.Add(100, "Inspiron");
      sortedDict.Add(200, "Alienware");
      sortedDict.Add(300, "Projectors");
      sortedDict.Add(400, "XPS");
      Console.WriteLine("SortedDictionary key-value pairs...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
      Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      Console.WriteLine("Count of SortedDictionary key-value pairs = "+sortedDict.Count);
      sortedDict.Add(800, "Notebook");
      sortedDict.Add(10000, "Bluetooth Speaker");
      Console.WriteLine("\nSortedDictionary key-value pairs...UPDATED");
      demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
      Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      Console.WriteLine("Count of SortedDictionary key-value pairs (UPDATED) = "+sortedDict.Count);
      sortedDict.Clear();
      Console.WriteLine("\nCount of SortedDictionary key-value pairs (UPDATED) = "+sortedDict.Count);
   }
}

실행 결과

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

SortedDictionary key-value pairs...
Key = 100, Value = Inspiron
Key = 200, Value = Alienware
Key = 300, Value = Projectors
Key = 400, Value = XPS
Count of SortedDictionary key-value pairs = 4
SortedDictionary key-value pairs...UPDATED
Key = 100, Value = Inspiron
Key = 200, Value = Alienware
Key = 300, Value = Projectors
Key = 400, Value = XPS
Key = 800, Value = Notebook
Key = 10000, Value = Bluetooth Speaker
Count of SortedDictionary key-value pairs (UPDATED) = 6
Count of SortedDictionary key-value pairs (UPDATED) = 0

정리

SortedDictionary.Clear() 메서드는 컬렉션 내의 모든 데이터를 손쉽게 초기화할 때 유용합니다. 반복문 없이 단 한 번의 호출로 전체 요소를 제거할 수 있으며, 제거 후에도 동일한 객체를 재사용할 수 있다는 점이 장점입니다. 다만 삭제된 데이터는 복구할 수 없으므로, 필요한 경우 미리 별도로 백업해 두는 것이 좋습니다.