LINQ 제한 연산자 (Where)
2022. 2. 1. 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
Where
입력 시퀀스를 제한하거나 필터링하여 출력 시퀀스를 생성
5보다 작은 수 가져오기
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums = from num in numbers
where num < 5
select num;
Console.WriteLine("Numbers < 5:");
foreach (var x in lowNums)
{
Console.WriteLine(x);
}
// output
Numbers < 5:
4
1
3
2
0
속성의 요소 필터링
List<Product> products = GetProductList();
// products List 에서 각 Product 의 UnitsInStock 의 값이 0 인것만 찾아오기
var soldOutProducts = from prod in products
where prod.UnitsInStock == 0
select prod;
Console.WriteLine("Sold out products:");
foreach (var product in soldOutProducts)
{
Console.WriteLine($"{product.ProductName} is sold out!");
}
//output
Sold out products:
Chef Anton's Gumbo Mix is sold out!
Alice Mutton is sold out!
Thuringer Rostbratwurst is sold out!
Gorgonzola Telino is sold out!
Perth Pasties is sold out!
여러 속성을 사용하여 요소 필터링
List<Product> products = GetProductList();
// UnitsInStock 이 0 보다 크고 UnitPrice 가 3.00M 보다 큰 Product 가져오기
var expensiveInStockProducts = from prod in products
where prod.UnitsInStock > 0 && prod.UnitPrice > 3.00M
select prod;
Console.WriteLine("In-stock products that cost more than 3.00:");
foreach (var product in expensiveInStockProducts)
{
Console.WriteLine($"{product.ProductName} is in stock and costs more than 3.00.");
}
인덱스를 기반으로 필터링
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
// digit 에 ditgits 의 object 가 들어가고 index 에 digits 의 인덱스가 자동으로 설정된다.
// 그걸 기반으로 각 object 의 length 가 index 보다 작은 것 을 필터링 한다.
var shortDigits = digits.Where((digit, index) => digit.Length < index);
Console.WriteLine("Short digits:");
foreach (var d in shortDigits)
{
Console.WriteLine($"The word {d} is shorter than its value.");
}
// output
The word five is shorter than its value.
The word six is shorter than its value.
The word seven is shorter than its value.
The word eight is shorter than its value.
The word nine is shorter than its value.
관련영상
반응형
'CSharp > Advance' 카테고리의 다른 글
LINQ Partition 연산자 (Take, Skip) (0) | 2022.02.03 |
---|---|
LINQ Projection 연산자 (Select) (0) | 2022.02.02 |
LINQ 란 (0) | 2022.01.31 |
제네릭 리플렉션 (Generic Reflection) (0) | 2022.01.28 |
제네릭 대리자 (Generic Delegate) (0) | 2022.01.27 |