C# SortedSet에서 조건자와 일치하는 요소 제거하기
C#의 SortedSet<T> 클래스는 지정된 조건자(predicate)를 만족하는 모든 요소를 한 번에 제거할 수 있는 RemoveWhere 메서드를 제공합니다. 이 메서드는 집합을 순회하면서 조건을 만족하는 요소를 삭제하며, 실제로 제거된 요소의 개수를 반환합니다. 아래 예제를 통해 사용 방법을 살펴보겠습니다.
예제 1: 10의 배수인 요소 모두 제거
다음 예제에서는 10으로 나누어 떨어지는(일의 자리가 0인) 모든 정수를 SortedSet에서 제거합니다.
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) {
SortedSet<int> set1 = new SortedSet<int>();
set1.Add(200);
set1.Add(215);
set1.Add(310);
set1.Add(500);
set1.Add(600);
Console.WriteLine("SortedSet elements...");
foreach (int i in set1) {
Console.WriteLine(i);
}
Console.WriteLine(" ");
set1.RemoveWhere(demo);
Console.WriteLine("SortedSet after removing some elements...");
foreach (int i in set1) {
Console.WriteLine(i);
}
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
SortedSet elements... 200 215 310 500 600 SortedSet after removing some elements... 215
출력에서 확인할 수 있듯이, 조건 (i % 10) == 0을 만족하는 200, 310, 500, 600이 모두 제거되고 10의 배수가 아닌 215만 남게 됩니다.
예제 2: 특정 값 하나만 제거
이번에는 조건자가 특정 값(500)과 일치할 때만 true를 반환하도록 작성하여 해당 요소 하나만 제거해 보겠습니다.
using System;
using System.Collections.Generic;
public class Demo {
private static bool demo(int i) {
return (i == 500);
}
public static void Main(String[] args) {
SortedSet<int> set1 = new SortedSet<int>();
set1.Add(200);
set1.Add(215);
set1.Add(310);
set1.Add(500);
set1.Add(600);
Console.WriteLine("SortedSet elements...");
foreach (int i in set1) {
Console.WriteLine(i);
}
Console.WriteLine(" ");
set1.RemoveWhere(demo);
Console.WriteLine("SortedSet after removing an element...");
foreach (int i in set1) {
Console.WriteLine(i);
}
}
}출력 결과
실행 결과는 다음과 같습니다.
SortedSet elements... 200 215 310 500 600 SortedSet after removing an element... 200 215 310 600
조건자가 값 500과 일치하는 요소에 대해서만 true를 반환하므로 500 하나만 제거되고, 나머지 네 개의 요소(200, 215, 310, 600)는 그대로 유지됩니다.
RemoveWhere 메서드 핵심 정리
- 시그니처:
public int RemoveWhere (Predicate<T> match); - 동작 방식: 집합의 각 요소에 대해 지정된
Predicate<T>대리자를 평가하여, true를 반환하는 모든 요소를 제거합니다. - 반환값: 실제로 제거된 요소의 총개수(int)를 반환합니다.
- 주의 사항: match 매개변수가 null이면
ArgumentNullException이 발생합니다.
이처럼 RemoveWhere 메서드를 활용하면 반복문과 별도의 임시 컬렉션 없이도 조건에 맞는 요소를 안전하고 간결하게 일괄 삭제할 수 있습니다.