C# Language Reference where clause (C# Reference)
The where clause is used in a query expression to specify which elements from the data source will be returned in the query expression. It applies a Boolean condition (predicate) to each source element (referenced by the range variable) and returns those for which the specified condition is true. A single query expression may contain multiple where clauses and a single clause may contain multiple predicate subexpressions.
 Example
In the following example, the where clause filters out all numbers except those that are less than five. If you remove the where clause, all numbers from the data source would be returned. The expression num < 5 is the predicate that is applied to each element. 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
Within a single where clause, you can specify as many predicates as necessary by using the && and || operators. In the following example, the query specifies two predicates in order to select only the even numbers that are less than five. 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() + " ");
}
}
}
// Output: 4 2 0
A where clause may contain one or more methods that return Boolean values. In the following example, the where clause uses a method to determine whether the current value of the range variable is even or odd. 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)
{
return i % 2 == 0;
}
}
//Output: 4 8 6 2 0
 Remarks
The where clause is a filtering mechanism. It can be positioned almost anywhere in a query expression, except it cannot be the first or last clause. A where clause may appear either before or after a group clause depending on whether you have to filter the source elements before or after they are grouped. If a specified predicate is not valid for the elements in the data source, a compile-time error will result. This is one benefit of the strong type-checking provided by LINQ.
At compile time the where keyword is converted into a call to the Where Standard Query Operator method.
 See Also
ConceptsReferenceOther Resources
|
C# Programmer's Reference onde cláusula (Referência C#)
A cláusula where é usada em uma expressão de consulta para especificar quais elementos da Origem de dados serão retornados na expressão de consulta. Ele se aplica a uma condição Booleanoa (predicado) a cada elemento de origem (referenciado pela variável de intervalo) e retorna os para o qual a condição especificada for Verdadeiro. Uma expressão de consulta simples pode conter várias cláusulas where e uma única cláusula pode conter Múltiplo subexpressions predicados.
 Exemplo
No exemplo a seguir, a cláusula where filtra Tudo números, exceto aqueles que são menos de cinco. Se você remover a cláusula de where, Tudo números da Origem de dados devem ser retornados. A expressão num < 5 é o predicado aplicado a cada elemento. 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
Em um Simples cláusula where , você pode especificar quantos predicados conforme necessário usando o e e || operadores. No exemplo a seguir, a consulta Especifica dois predicados em Ordem para selecionar apenas os números de par que são menos de cinco. 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() + " ");
}
}
}
// Output: 4 2 0
Uma cláusula where pode conter um ou mais métodos que retornam valores booleanos. No exemplo a seguir, a cláusula where usa um método para determinar se o valor atual da variável de intervalo é par ou ímpar. 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)
{
return i % 2 == 0;
}
}
//Output: 4 8 6 2 0
 Comentários
A cláusula where é um mecanismo de filtragem. Ele pode ser posicionado em quase qualquer lugar em uma expressão de consulta, exceto que ele não pode ser a cláusula Primeiro ou Último. Uma cláusula where pode aparecer antes ou após uma cláusula de grupo dependendo se você tem para Filtro os elementos de origem antes ou depois que elas são agrupadas. Se um predicado especificado não for válido para os elementos na Origem de dados, ocorrerá um erro de tempo de Compilar. Isso é uma vantagem do forte tipo-verificação fornecida pelo LINQ.
Em tempo de Compilar a palavra-chave where é convertida em uma chamada para o Where método operador de consulta padrão.
 Consulte também
ConceitosReferênciaOutros recursos
|