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

C# HashSet에서 모든 요소 제거하기 – Clear() 메서드 완벽 가이드


HashSet<T>는 중복을 허용하지 않는 고유한 요소들의 집합을 저장하는 C# 대표 컬렉션입니다. 이 HashSet에 담긴 모든 요소를 한 번에 제거(초기화)하려면 Clear() 메서드를 호출하면 됩니다. Clear() 메서드가 실행되면 컬렉션 내부의 모든 항목이 삭제되고, Count 속성 값이 0으로 변경됩니다.

예제 1 – 두 개의 HashSet 생성 후 요소 제거하기

아래 예제에서는 문자열 타입의 HashSet을 두 개 생성하고 각각의 요소를 출력합니다. 이후 두 집합이 동일한지 비교하고, Clear() 메서드를 사용해 HashSet2의 모든 요소를 제거합니다.

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(String[] args){
      HashSet<string> set1 = new HashSet<string>();
      set1.Add("A");
      set1.Add("B");
      set1.Add("C");
      set1.Add("D");
      set1.Add("E");
      set1.Add("F");
      set1.Add("G");
      set1.Add("H");
      Console.WriteLine("Elements in HashSet1...");
      foreach (string res in set1){
         Console.WriteLine(res);
      }

      HashSet<string> set2 = new HashSet<string>();
      set2.Add("John");
      set2.Add("Jacob");
      set2.Add("Ryan");
      set2.Add("Tom");
      set2.Add("Andy");
      set2.Add("Tim");
      set2.Add("Steve");
      set2.Add("Mark");
      Console.WriteLine("Elements in HashSet2...");
      foreach (string res in set2){
         Console.WriteLine(res);
      }

      Console.WriteLine("Is HashSet1 equal to HashSet2? = " + set1.Equals(set2));
      Console.WriteLine("Count of HashSet2 = " + set2.Count);

      // HashSet2의 모든 요소 제거
      set2.Clear();
      Console.WriteLine("Count of HashSet2 (updated) = " + set2.Count);
   }
}

실행 결과

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

Elements in HashSet1...
A
B
C
D
E
F
G
H
Elements in HashSet2...
John
Jacob
Ryan
Tom
Andy
Tim
Steve
Mark
Is HashSet1 equal to HashSet2? = False
Count of HashSet2 = 8
Count of HashSet2 (updated) = 0

예제 2 – 단일 HashSet 초기화하기

이번에는 하나의 HashSet만 사용해 요소를 추가한 뒤, Clear() 메서드로 전체 요소를 제거하는 더 간단한 예제를 살펴보겠습니다.

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(String[] args){
      HashSet<string> set1 = new HashSet<string>();
      set1.Add("A");
      set1.Add("B");
      set1.Add("C");
      set1.Add("D");
      set1.Add("E");
      set1.Add("F");
      set1.Add("G");
      set1.Add("H");
      Console.WriteLine("Elements in HashSet...");
      foreach (string res in set1){
         Console.WriteLine(res);
      }
      Console.WriteLine("Count of HashSet1 = " + set1.Count);

      // HashSet1의 모든 요소 제거
      set1.Clear();
      Console.WriteLine("Count of HashSet1 (updated) = " + set1.Count);
   }
}

실행 결과

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

Elements in HashSet...
A
B
C
D
E
F
G
H
Count of HashSet1 = 8
Count of HashSet1 (updated) = 0

핵심 정리

  • HashSet의 모든 요소를 한 번에 제거하려면 Clear() 메서드를 사용합니다.
  • Clear() 메서드 호출 후 Count 속성은 0으로 변경됩니다.
  • Remove() 메서드가 특정 요소 하나만 제거하는 것과 달리, Clear()는 컬렉션 전체를 비우는 데 사용됩니다.
  • 요소 제거 후에도 HashSet 객체 자체는 유효하므로, 같은 객체에 새로운 요소를 계속 추가할 수 있습니다.