C# HashSet에서 항목 제거하기 – RemoveWhere 메서드 활용법
C#의 HashSet<T>는 중복을 허용하지 않는 고유한 요소들의 집합을 나타내는 컬렉션입니다. 이 집합에서 특정 조건에 맞는 항목을 제거하려면 RemoveWhere 메서드를 사용하면 됩니다.
1단계: HashSet 선언 및 요소 추가
먼저 HashSet을 선언하고 문자열 요소들을 추가합니다.
var names = new HashSet<string>();
names.Add("Tim");
names.Add("John");
names.Add("Tom");
names.Add("Kevin");2단계: RemoveWhere로 항목 제거
RemoveWhere 메서드는 람다 식 형태의 조건자(predicate)를 인수로 받아, 해당 조건을 만족하는 모든 요소를 한 번에 제거합니다. 다음 코드는 이름이 "John"과 일치하는 항목을 삭제합니다.
names.RemoveWhere(x => x == "John");
참고로 RemoveWhere는 실제로 제거된 요소의 개수를 정수(int)로 반환하므로, 몇 개의 항목이 삭제되었는지 확인하는 용도로도 활용할 수 있습니다.
전체 예제 코드
지금까지의 내용을 하나로 정리한 완전한 예제입니다. 초기 집합을 출력한 뒤 항목을 제거하고, 그 결과를 다시 화면에 표시합니다.
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
var names = new HashSet<string>();
names.Add("Tim");
names.Add("John");
names.Add("Tom");
names.Add("Kevin");
Console.WriteLine("Initial Set...");
foreach(var val in names) {
Console.WriteLine(val);
}
names.RemoveWhere(x => x == "John");
Console.WriteLine("Set after removing an element...");
foreach(var val in names) {
Console.WriteLine(val);
}
}
}실행 결과
Initial Set... Tim John Tom Kevin Set after removing an element... Tim Tom Kevin
이처럼 RemoveWhere를 사용하면 별도의 반복문 없이도 조건에 맞는 항목을 간결하고 효율적으로 제거할 수 있습니다.