Linq 집합 연산자 (Set Operators)

2022. 2. 8. 00:00CSharp/Advance

반응형

여러 데이터 집합을 비교하는 기능을 제공

교집합, 합집합, 모든 고유한 요소 및 집합 간의 차이를 찾을 수 있다.

 

고유한 요소 찾기 (Distinct)

int[] factorsOf300 = { 2, 2, 3, 5, 5 };
var uniqueFactors = factorsOf300.Distinct();
Console.WriteLine("Prime factors of 300:");
foreach (var f in uniqueFactors)
{
    Console.WriteLine(f);
}

//output
Prime factors of 300:
2
3
5

고유 속성 요소 찾기

아래 예제는 고유한 category 를 찾아온다.

List<Product> products = GetProductList();

var categoryNames = (from p in products
                     select p.Category)
                     .Distinct();

Console.WriteLine("Category names:");
foreach (var n in categoryNames)
{
    Console.WriteLine(n);
}

// output
Category names:
Beverages
Condiments
Produce
Meat/Poultry
Seafood
Dairy Products
Confections
Grains/Cereals

합집합 (Union)

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };

var uniqueNumbers = numbersA.Union(numbersB);

Console.WriteLine("Unique numbers from both arrays:");
foreach (var n in uniqueNumbers)
{
    Console.Write($"{n} ");
}

//output
Unique numbers from both arrays:
0 2 4 5 6 8 9 1 3 7

교집합 (Intersect)

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };

var commonNumbers = numbersA.Intersect(numbersB);

Console.WriteLine("Common numbers shared by both arrays:");
foreach (var n in commonNumbers)
{
    Console.WriteLine(n);
}

//output
Common numbers shared by both arrays:
5
8

차집합 (Except)

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };

IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB);

Console.WriteLine("Numbers in first array but not second array:");
foreach (var n in aOnlyNumbers)
{
    Console.WriteLine(n);
}

// output
Numbers in first array but not second array:
0
2
4
6
9

 

관련영상

https://youtu.be/CsMsPAOg7d0

 

반응형