C#에서 두 리스트(List)의 차이, 즉 한쪽에는 있지만 다른 쪽에는 없는 요소들을 구하려면 먼저 비교 대상이 되는 두 개의 리스트를 준비해야 합니다.
1. 두 리스트 준비하기
먼저 문자열을 담는 두 개의 리스트를 만들고 요소를 추가합니다.
// 첫 번째 리스트
List<string> list1 = new List<string>();
list1.Add("A");
list1.Add("B");
list1.Add("C");
list1.Add("D");
// 두 번째 리스트
List<string> list2 = new List<string>();
list2.Add("C");
list2.Add("D");위 코드에서 list1에는 A, B, C, D가 들어 있고, list2에는 C, D만 들어 있습니다.
2. Except() 메서드로 차집합 구하기
두 리스트의 차이를 구할 때는 LINQ에서 제공하는 Except() 메서드를 사용합니다. 이 메서드는 첫 번째 컬렉션에는 포함되지만 두 번째 컬렉션에는 없는 요소들만 반환하며, 그 결과는 IEnumerable<T> 타입으로 받습니다.
IEnumerable<string> list3;
list3 = list1.Except(list2);Except()를 사용하려면 파일 상단에 using System.Linq; 네임스페이스 선언이 반드시 필요합니다. 또한 이 메서드는 집합 연산을 기반으로 동작하기 때문에 중복된 값은 하나로 처리된다는 점도 기억해 두면 좋습니다.
3. 전체 예제 코드
지금까지 설명한 내용을 모두 합친 완성된 코드는 다음과 같습니다.
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
List<string> list1 = new List<string>();
list1.Add("A");
list1.Add("B");
list1.Add("C");
list1.Add("D");
Console.WriteLine("First list...");
foreach(string value in list1) {
Console.WriteLine(value);
}
Console.WriteLine("Second list...");
List<string> list2 = new List<string>();
list2.Add("C");
list2.Add("D");
foreach(string value in list2) {
Console.WriteLine(value);
}
Console.WriteLine("Difference in the two lists...");
IEnumerable<string> list3;
list3 = list1.Except(list2);
foreach(string value in list3) {
Console.WriteLine(value);
}
}
}4. 실행 결과
First list...
A
B
C
D
Second list...
C
D
Difference in the two lists...
A
B실행 결과를 보면 list1에만 존재하고 list2에는 없는 A와 B가 차이로 출력되는 것을 확인할 수 있습니다. list1과 list2 양쪽 모두에 있는 C와 D는 결과에서 제외됩니다.
정리
Except()메서드를 사용하면 두 컬렉션의 차집합을 간단하게 구할 수 있습니다.- 결과는
IEnumerable<T>타입으로 반환되며,foreach문으로 순회하여 출력할 수 있습니다. - 사용 시
System.Linq네임스페이스를 참조해야 하며, 중복 요소는 집합 연산 규칙에 따라 하나만 남게 됩니다.