| title | ms.date | ms.prod | ms.technology | ms.topic | f1_keywords | dev_langs | helpviewer_keywords | ms.assetid | caps.latest.revision | author | ms.author | translation.priority.ht | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
where clause (C# Reference) |
2015-07-20 |
.net |
|
article |
|
|
|
7f9bf952-7744-4f91-b676-cddb55d107c3 |
16 |
BillWagner |
wiwagn |
|
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.
[!code-cscscsrefQueryKeywords#5]
Example
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.
[!code-cscscsrefQueryKeywords#6]
Example
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.
[!code-cscscsrefQueryKeywords#7]
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 [!INCLUDEvbteclinq].
At compile time the where keyword is converted into a call to the xref:System.Linq.Enumerable.Where%2A Standard Query Operator method.
See Also
Query Keywords (LINQ)
from clause
select clause
Filtering Data
LINQ Query Expressions
Getting Started with LINQ in C#