LINQ Projection 연산자 (Select)
2022. 2. 2. 00:00ㆍCSharp/Advance
반응형
ProductList 와 CusomerList 는 아래 sample 참고
https://github.com/dotnet/try-samples/tree/main/101-linq-samples/src/DataSources
GitHub - dotnet/try-samples
Contribute to dotnet/try-samples development by creating an account on GitHub.
github.com
select
입력 시퀀스 요소에서 출력 시퀀스 요소를 생성. 출력 요소는 동일하거나 다른 유형일 수 있다.
기본구조
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
// n 을 가져와서 +1 을 하여 저장
var numsPlusOne = from n in numbers
select n + 1;
Console.WriteLine("Numbers + 1:");
foreach (var i in numsPlusOne)
{
Console.WriteLine(i);
}
// Output
Numbers + 1:
6
5
2
4
10
9
7
8
3
1
익명 유형 또는 튜플
string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };
// words 를 가져와서 Upper 에 대문자로 , Lower 에 소문자로 Anonymous 로 저장
var upperLowerWords = from w in words
select new { Upper = w.ToUpper(), Lower = w.ToLower() };
foreach (var ul in upperLowerWords)
{
Console.WriteLine($"Uppercase: {ul.Upper}, Lowercase: {ul.Lower}");
}
// Output
Uppercase: APPLE, Lowercase: apple
Uppercase: BLUEBERRY, Lowercase: blueberry
Uppercase: CHERRY, Lowercase: cherry
string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };
// words 를 가져와서 Upper 에 대문자로 , Lower 에 소문자로 Tuple 로 저장
var upperLowerWords = from w in words
select (Upper: w.ToUpper(), Lower: w.ToLower());
foreach (var ul in upperLowerWords)
{
Console.WriteLine($"Uppercase: {ul.Upper}, Lowercase: {ul.Lower}");
}
// Output
Uppercase: APPLE, Lowercase: apple
Uppercase: BLUEBERRY, Lowercase: blueberry
Uppercase: CHERRY, Lowercase: cherry
인덱스를 사용하여 소스항목 선택
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numsInPlace = numbers.Select((num, index) => (Num: num, InPlace: (num == index)));
Console.WriteLine("Number: In-place?");
foreach (var n in numsInPlace)
{
Console.WriteLine($"{n.Num}: {n.InPlace}");
}
//Output
Number: In-place?
5: False
4: False
1: False
3: True
9: False
8: False
6: True
7: True
2: False
0: False
하위 항목의 요소로 필터링
var orders = from c in customers
from o in c.Orders
where o.Total < 500.00M
select (c.CustomerID, o.OrderID, o.Total);
foreach (var order in orders)
{
Console.WriteLine($"Customer: {order.CustomerID}, Order: {order.OrderID}, Total value: {order.Total}");
}
다중 필터로 다중 선택
List<Customer> customers = GetCustomerList();
DateTime cutoffDate = new DateTime(1997, 1, 1);
var orders = from c in customers
where c.Region == "WA"
from o in c.Orders
where o.OrderDate >= cutoffDate
select (c.CustomerID, o.OrderID);
foreach (var order in orders)
{
Console.WriteLine($"Customer: {order.CustomerID}, Order: {order.OrderID}");
}
관련영상
반응형
'CSharp > Advance' 카테고리의 다른 글
LINQ 순서정렬 연산자 (OrderBy) (0) | 2022.02.04 |
---|---|
LINQ Partition 연산자 (Take, Skip) (0) | 2022.02.03 |
LINQ 제한 연산자 (Where) (0) | 2022.02.01 |
LINQ 란 (0) | 2022.01.31 |
제네릭 리플렉션 (Generic Reflection) (0) | 2022.01.28 |