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

C# Hashtable에서 모든 요소 한 번에 제거하기 – Clear() 메서드 활용법

C# Hashtable에서 모든 요소 제거하기

C#의 Hashtable에 저장된 모든 키-값 쌍을 한 번에 삭제하려면 Clear() 메서드를 사용하면 됩니다. Clear()를 호출하면 Hashtable 내부의 모든 요소가 제거되고 Count 속성 값이 0으로 초기화됩니다.

아래 예제를 통해 실제 동작 과정을 살펴보겠습니다.

예제 1 – Clear()로 전체 요소 제거

using System;
using System.Collections;

public class Demo {
   public static void Main() {
      Hashtable hash = new Hashtable(10);

      hash.Add("1", "A");
      hash.Add("2", "B");
      hash.Add("3", "C");
      hash.Add("4", "D");
      hash.Add("5", "E");
      hash.Add("6", "F");
      hash.Add("7", "G");
      hash.Add("8", "H");
      hash.Add("9", "I");
      hash.Add("10", "J");

      Console.WriteLine("Hashtable의 키와 값 쌍...");
      foreach(DictionaryEntry entry in hash) {
         Console.WriteLine("{0} : {1}", entry.Key, entry.Value);
      }

      Console.WriteLine("Hashtable이 고정 크기인가요? = " + hash.IsFixedSize);
      Console.WriteLine("Hashtable의 항목 수 = " + hash.Count);

      hash.Clear();

      Console.WriteLine("Hashtable의 항목 수 (초기화 후) = " + hash.Count);
   }
}

출력 결과

위 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.

Hashtable의 키와 값 쌍...
10 : J
1 : A
2 : B
3 : C
4 : D
5 : E
6 : F
7 : G
8 : H
9 : I
Hashtable이 고정 크기인가요? = False
Hashtable의 항목 수 = 10
Hashtable의 항목 수 (초기화 후) = 0

코드 설명

  • Add(key, value) – Hashtable에 새로운 키와 값을 추가합니다.
  • IsFixedSize – Hashtable이 고정 크기인지 여부를 나타냅니다. 일반적인 Hashtable은 크기가 동적으로 조절되므로 False가 출력됩니다.
  • Count – Hashtable에 현재 저장된 요소의 개수를 반환합니다.
  • Clear() – Hashtable의 모든 요소를 제거하고 Count를 0으로 만듭니다. 단, 내부 버킷의 용량(capacity)은 그대로 유지됩니다.

참고로 Hashtable은 해시 기반 컬렉션이므로 foreach로 순회할 때 요소의 출력 순서는 입력 순서와 다르게 나타날 수 있습니다.

예제 2 – 문자열 키를 사용하는 경우

이번에는 문자열 키를 사용하는 Hashtable에 Clear() 메서드를 적용해 보겠습니다.

using System;
using System.Collections;

public class Demo {
   public static void Main() {
      Hashtable hash = new Hashtable(10);

      hash.Add("One", "100");
      hash.Add("Two", "200");
      hash.Add("Three", "300");
      hash.Add("Four", "400");
      hash.Add("Five", "500");

      Console.WriteLine("Hashtable의 키와 값 쌍...");
      foreach(DictionaryEntry entry in hash) {
         Console.WriteLine("{0} : {1}", entry.Key, entry.Value);
      }

      Console.WriteLine("Hashtable의 항목 수 = " + hash.Count);

      hash.Clear();

      Console.WriteLine("Hashtable의 항목 수 (초기화 후) = " + hash.Count);
   }
}

출력 결과

Hashtable의 키와 값 쌍...
One : 100
Five : 500
Three : 300
Two : 200
Four : 400
Hashtable의 항목 수 = 5
Hashtable의 항목 수 (초기화 후) = 0

정리

Hashtable의 모든 요소를 제거할 때는 각 항목을 Remove()로 하나씩 삭제하는 것보다 Clear() 메서드를 사용하는 것이 더 간결하고 효율적입니다. Clear() 호출 후에는 Count가 0이 되지만, Hashtable 객체 자체는 그대로 유지되므로 이후에 새로운 데이터를 계속 추가할 수 있다는 점도 기억해 두면 좋습니다.