where 子句 (C# 參考)

在查詢運算式中,where 子句是用來指定資料來源的哪個項目將會在查詢運算式中傳回。 它會將布林值 (Boolean) 條件 (「述詞」(Predicate)) 套用到每個來源項目 (由範圍變數參考),並傳回指定條件為 True 的項目。 單一查詢運算式可能包含多個 where 子句,而且單一子句可能包含多個述詞子運算式 (Subexpression)。

範例

在下列範例中,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

在單一 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() + " ");
        }            
    }
}
// Output: 4 2 0

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)
    {
        return i % 2 == 0;
    }    
}
//Output: 4 8 6 2 0

備註

where 子句是一項篩選機制。 它可以放置在查詢運算式的絕大多數位置,除了不能放置在第一個或最後一個子句中。 where 子句會根據需要在來源項目完成分組之前或之後篩選來源項目,而出現在 group 子句的之前或之後。

如果指定的述詞對於資料來源中的項目無效,便會造成編譯時期錯誤。 這是 LINQ 所提供強型別檢查的其中一項優點。

在編譯時期,where 關鍵字便會轉換成對 Where 標準查詢運算子方法的呼叫。

請參閱

參考

from 子句 (C# 參考)

select 子句 (C# 參考)

概念

篩選資料

LINQ 查詢運算式 (C# 程式設計手冊)

其他資源

查詢關鍵字 (C# 參考)

開始使用 C# 中的 LINQ