기타/C#
LINQ 집합
Krapboss
2024. 7. 23. 23:17
두 시퀀스의 교집합을 구하는
Intersect
public static System.Collections.Generic.IEnumerable<TSource> Intersect<TSource> (this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second);
반환
IEnumerable<TSource> 두 시퀀스의 교집합을 이루는 요소가 들어 있는 시퀀스입니다.
예외
ArgumentNullExceptionfirst 또는 second가 null인 경우
int[] id1 = { 44, 26, 92, 30, 71, 38 };
int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };
IEnumerable<int> both = id1.Intersect(id2);
foreach (int id in both)
Console.WriteLine(id);
/*
This code produces the following output:
26
30
*/
+사용자 정의 가능
https://learn.microsoft.com/ko-kr/dotnet/api/system.linq.enumerable.intersect?view=net-8.0
두 시퀀스의 차집합을 구하는
Except
Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)
기본 같음 비교자로 값을 비교하여 두 시퀀스의 차집합을 구합니다.
반환
IEnumerable<TSource>
두 시퀀스 요소의 차집합이 들어 있는 시퀀스입니다.
예외
ArgumentNullExceptionfirst 또는 second가 null인 경우
+지연된 실행
Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)
지정된 IEqualityComparer<T>로 값을 비교하여 두 시퀀스의 차집합을 구합니다.
*차집합
double[] numbers1 = { 2.0, 2.0, 2.1, 2.2, 2.3, 2.3, 2.4, 2.5 };
double[] numbers2 = { 2.2 };
IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2);
foreach (double number in onlyInFirstSet)
Console.WriteLine(number);
/*
This code produces the following output:
2
2.1
2.3
2.4
2.5
*/
* 사용자 정의
https://learn.microsoft.com/ko-kr/dotnet/api/system.linq.enumerable.except?view=net-8.0
두 시퀀스의 합집합을 구하는
Union
예외
ArgumentNullException first 또는 second가 null인 경우
기본
int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 };
int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 };
IEnumerable<int> union = ints1.Union(ints2);
foreach (int num in union)
{
Console.Write("{0} ", num);
}
/*
This code produces the following output:
5 3 9 7 8 6 4 1 0
*/
사용자 정의