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

C# HashSet에서 조건(Predicate)을 기준으로 요소 제거하는 방법 – RemoveWhere 완벽 가이드

C#의 HashSet<T> 컬렉션에서 특정 조건을 만족하는 요소들을 한 번에 제거하려면 RemoveWhere() 메서드를 사용하면 됩니다. 이 메서드는 조건자(Predicate)를 매개변수로 받아, 해당 조건이 참(true)을 반환하는 모든 요소를 집합에서 삭제합니다.

RemoveWhere() 메서드란?

RemoveWhere 메서드는 Predicate<T> 대리자를 인수로 받으며, 컬렉션을 순회하면서 각 요소에 대해 조건을 검사한 뒤 조건에 부합하는 요소만 제거하고, 실제로 제거된 요소의 개수를 반환합니다.

예제 1: 특정 값과 일치하는 요소 제거하기

다음 예제는 값이 100인 요소를 조건으로 정의하여 HashSet에서 제거하는 코드입니다.

using System;
using System.Collections.Generic;

public class Demo {
   private static bool demo(int i) {
      return (i == 100);
   }

   public static void Main(String[] args) {
      HashSet<int> list = new HashSet<int>();
      list.Add(100);
      list.Add(300);
      list.Add(400);
      list.Add(500);
      list.Add(600);

      Console.WriteLine("HashSet 요소 목록...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }

      Console.WriteLine(" ");
      list.RemoveWhere(demo);

      Console.WriteLine("100 제거 후 HashSet...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
   }
}

출력 결과

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

HashSet 요소 목록...
100
300
400
500
600
100 제거 후 HashSet...
300
400
500
600

예제 2: 복합 조건으로 여러 요소 제거하기

조건자는 하나의 값뿐 아니라 다양한 논리 조건을 포함할 수 있습니다. 아래 예제는 10으로 나누어 떨어지는(즉, 일의 자리가 0인) 모든 요소를 제거하는 코드입니다.

using System;
using System.Collections.Generic;

public class Demo {
   private static bool demo(int i) {
      return ((i % 10) == 0);
   }

   public static void Main(String[] args) {
      HashSet<int> list = new HashSet<int>();
      list.Add(100);
      list.Add(355);
      list.Add(400);
      list.Add(555);
      list.Add(600);

      Console.WriteLine("HashSet 요소 목록...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }

      Console.WriteLine(" ");
      list.RemoveWhere(demo);

      Console.WriteLine("일부 요소 제거 후 HashSet...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
   }
}

출력 결과

실행 결과는 다음과 같습니다. 10의 배수인 100, 400, 600이 제거되고 나머지 요소만 남습니다.

HashSet 요소 목록...
100
355
400
555
600
일부 요소 제거 후 HashSet...
355
555

정리

C#에서 HashSet의 요소를 조건에 따라 제거할 때는 RemoveWhere() 메서드가 가장 간결하고 효율적인 방법입니다. 람다 식을 활용하면 별도의 메서드 정의 없이 list.RemoveWhere(x => x == 100);처럼 한 줄로 처리할 수도 있으므로, 상황에 맞게 활용해 보시기 바랍니다.