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

C# HashSet에서 다른 컬렉션에 포함된 모든 요소 제거하기 – ExceptWith 메서드 완벽 가이드

C#에서 HashSet에 담긴 요소 중 다른 컬렉션에도 존재하는 요소들을 한 번에 제거하고 싶다면 ExceptWith() 메서드를 사용하면 됩니다. 이 메서드는 현재 HashSet에서 지정한 컬렉션에 포함된 모든 요소를 찾아 제거하는 역할을 하며, 수학의 차집합 연산과 동일한 개념입니다.

ExceptWith 메서드란?

ExceptWith(IEnumerable<T> other)는 매개변수로 전달된 컬렉션에 있는 요소들을 현재 HashSet에서 모두 삭제합니다. 이때 원본 컬렉션(other)은 변경되지 않고, 호출한 HashSet만 수정됩니다.

예제 1: 두 HashSet 비교 후 차집합 구하기

다음은 set2에서 set1에 포함된 요소들을 모두 제거하는 예제입니다.

using System;
using System.Collections.Generic;
public class Demo {
    public static void Main(String[] args){
        HashSet<string> set1 = new HashSet<string>();
        set1.Add("Ryan");
        set1.Add("Tom");
        set1.Add("Andy");
        set1.Add("Tim");
        Console.WriteLine("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("HashSet2의 요소들...");
        foreach (string res in set2){
            Console.WriteLine(res);
        }
        Console.WriteLine("HashSet1과 HashSet2가 같은가? = " + set1.Equals(set2));
        // set1에 포함된 요소들을 set2에서 모두 제거
        set2.ExceptWith(set1);
        // set1에는 없는 set2의 요소만 출력
        foreach(string i in set2){
            Console.WriteLine(i);
        }
    }
}

실행 결과

HashSet1의 요소들...
Ryan
Tom
Andy
Tim
HashSet2의 요소들...
John
Jacob
Ryan
Tom
Andy
Tim
Steve
Mark
HashSet1과 HashSet2가 같은가? = False
John
Jacob
Steve
Mark

실행 결과를 보면 set2에 있던 8개의 요소 중 set1에도 포함되어 있던 Ryan, Tom, Andy, Tim이 제거되고, John, Jacob, Steve, Mark 네 개의 요소만 남은 것을 확인할 수 있습니다.

예제 2: 대부분 겹치는 경우의 차집합

이번에는 두 집합이 거의 동일하고 한쪽에만 존재하는 요소가 하나뿐인 경우를 살펴보겠습니다.

using System;
using System.Collections.Generic;
public class Demo {
    public static void Main(String[] args){
        HashSet<string> set1 = new HashSet<string>();
        set1.Add("Jacob");
        set1.Add("Ryan");
        set1.Add("Tom");
        set1.Add("Andy");
        set1.Add("Tim");
        set1.Add("Steve");
        set1.Add("Mark");
        Console.WriteLine("HashSet1의 요소들...");
        foreach (string res in set1){
            Console.WriteLine(res);
        }
        HashSet<string> set2 = new HashSet<string>();
        set2.Add("Kevin");
        set2.Add("Jacob");
        set2.Add("Ryan");
        set2.Add("Tom");
        set2.Add("Andy");
        set2.Add("Tim");
        set2.Add("Steve");
        set2.Add("Mark");
        Console.WriteLine("HashSet2의 요소들...");
        foreach (string res in set2){
            Console.WriteLine(res);
        }
        Console.WriteLine("HashSet1과 HashSet2가 같은가? = " + set1.Equals(set2));
        // set1에 포함된 요소들을 set2에서 모두 제거
        set2.ExceptWith(set1);
        // set1에는 없는 set2의 요소만 출력
        foreach(string i in set2){
            Console.WriteLine(i);
        }
    }
}

실행 결과

HashSet1의 요소들...
Jacob
Ryan
Tom
Andy
Tim
Steve
Mark
HashSet2의 요소들...
Kevin
Jacob
Ryan
Tom
Andy
Tim
Steve
Mark
HashSet1과 HashSet2가 같은가? = False
Kevin

set2에는 set1의 모든 요소가 포함되어 있고, set2에만 존재하는 유일한 요소는 Kevin입니다. 따라서 ExceptWith(set1) 실행 후 set2에는 Kevin 하나만 남게 됩니다.

정리

  • ExceptWith()는 현재 HashSet에서 지정한 컬렉션과 겹치는 요소를 모두 제거하는 차집합 연산 메서드입니다.
  • 매개변수로 전달된 컬렉션은 변경되지 않으며, 호출한 HashSet만 수정됩니다.
  • 시간 복잡도는 O(n)으로, 컬렉션 크기에 비례하여 효율적으로 동작합니다.