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. 它會將布林值條件 (predicate) 套用到每個來源項目 (透過範圍變數所參考),並傳回所指定條件為 true 的項目。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. 這是 LINQLINQ 所提供的強類型檢查的其中一個優點。This is one benefit of the strong type-checking provided by LINQLINQ.

在編譯時間,where 關鍵字會轉換為 Where 標準查詢運算子方法呼叫。At compile time the where keyword is converted into a call to the Where Standard Query Operator method.

另請參閱See also