where 子句(C# 参考)where clause (C# Reference)

where 子句用在查询表达式中,用于指定将在查询表达式中返回数据源中的哪些元素。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. 一个查询表达式可以包含多个 where 子句,一个子句可以包含多个谓词子表达式。A single query expression may contain multiple where clauses and a single clause may contain multiple predicate subexpressions.

示例Example

在下面的示例中,where 子句筛选出除小于五的数字外的所有数字。In the following example, the where clause filters out all numbers except those that are less than five. 如果删除 where 子句,则会返回数据源中的所有数字。If you remove the where clause, all numbers from the data source would be returned. 表达式 num < 5 是应用于每个元素的谓词。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

示例Example

在单个 where 子句中,可以使用 &&|| 运算符根据需要指定任意多个谓词。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() + " ");
        }
        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

示例Example

一个 where 子句可以包含一个或多个返回布尔值的方法。A where clause may contain one or more methods that return Boolean values. 在下面的示例中,where 子句使用一种方法来确定范围变量的当前值是偶数还是奇数。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

where 子句是一种筛选机制。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. where 子句可以出现在 group 子句的前面或后面,具体取决于时必须在对源元素进行分组之前还是之后来筛选源元素。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. 这是 LINQ 提供的强类型检查的一个优点。This is one benefit of the strong type-checking provided by LINQ.

在编译时,where 关键字将转换为对 Where 标准查询运算符方法的调用。At compile time the where keyword is converted into a call to the Where Standard Query Operator method.

请参阅See also