이 where 절은 쿼리 식에서 반환될 데이터 원본의 요소를 지정하기 위해 쿼리 식에 사용됩니다. 각 소스 요소(범위 변수에서 참조)에 부울 조건자(조건자)를 적용하고 지정된 조건이 true인 조건을 반환합니다. 단일 쿼리 식에는 여러 where 절이 포함될 수 있으며 단일 절에는 여러 조건자 하위 식이 포함될 수 있습니다.
예제 1
다음 예제에서 절은 where 5보다 작은 숫자를 제외한 모든 숫자를 필터링합니다. 절을 where 제거하면 데이터 원본의 모든 숫자가 반환됩니다. 식 num < 5 은 각 요소에 적용되는 조건자입니다.
class WhereSample
{
static void Main()
{
// Simple data source. Arrays support IEnumerable<T>.
int[] numbers = [5, 4, 1, 3, 9, 8, 6, 7, 2, 0];
// Simple query with one predicate in where clause.
var queryLowNums =
from num in numbers
where num < 5
select num;
// Execute the query.
foreach (var s in queryLowNums)
{
Console.Write(s.ToString() + " ");
}
}
}
//Output: 4 1 3 2 0
예제 2
단일 where 절 내에서 &&|| 연산자를 사용하여 필요한 만큼 조건자를 지정할 수 있습니다. 다음 예제에서 쿼리는 5보다 작은 짝수만 선택하기 위해 두 개의 조건자를 지정합니다.
class WhereSample2
{
static void Main()
{
// Data source.
int[] numbers = [5, 4, 1, 3, 9, 8, 6, 7, 2, 0];
// Create the query with two predicates in where clause.
var queryLowNums2 =
from num in numbers
where num < 5 && num % 2 == 0
select num;
// Execute the query
foreach (var s in queryLowNums2)
{
Console.Write(s.ToString() + " ");
}
Console.WriteLine();
// Create the query with two where clause.
var queryLowNums3 =
from num in numbers
where num < 5
where num % 2 == 0
select num;
// Execute the query
foreach (var s in queryLowNums3)
{
Console.Write(s.ToString() + " ");
}
}
}
// Output:
// 4 2 0
// 4 2 0
예제 3
절에는 where 부울 값을 반환하는 메서드가 하나 이상 포함될 수 있습니다. 다음 예제에서 절은 where 메서드를 사용하여 범위 변수의 현재 값이 짝수인지 홀수인지 확인합니다.
class WhereSample3
{
static void Main()
{
// Data source
int[] numbers = [5, 4, 1, 3, 9, 8, 6, 7, 2, 0];
// Create the query with a method call in the where clause.
// Note: This won't work in LINQ to SQL unless you have a
// stored procedure that is mapped to a method by this name.
var queryEvenNums =
from num in numbers
where IsEven(num)
select num;
// Execute the query.
foreach (var s in queryEvenNums)
{
Console.Write(s.ToString() + " ");
}
}
// Method may be instance method or static method.
static bool IsEven(int i) => i % 2 == 0;
}
//Output: 4 8 6 2 0
비고
절은 where 필터링 메커니즘입니다. 첫 번째 또는 마지막 절이 될 수 없다는 점을 제외하고 쿼리 식의 거의 모든 위치에 배치할 수 있습니다.
where 그룹화 전이나 후에 원본 요소를 필터링해야 하는지 여부에 따라 그룹 절 앞이나 후에 절이 나타날 수 있습니다.
데이터 원본의 요소에 대해 지정된 조건자가 유효하지 않으면 컴파일 시간 오류가 발생합니다. 이는 LINQ에서 제공하는 강력한 형식 검사의 한 가지 이점입니다.
컴파일 시 where 키워드는 표준 쿼리 연산자 메서드에 대한 Where 호출로 변환됩니다.
참고하십시오
.NET