共用方式為


where 子句 (C# 參考)

where 句會用於查詢表示式中,以指定查詢表達式中會傳回數據源的專案。 它會將布爾值條件(述詞)套用至每個來源專案(由範圍變數參考),並傳回指定條件為 true 的元素。 單一查詢表達式可能包含多個 where 子句,而單一子句可能包含多個述詞子表達式。

範例 1

在下列範例中 where ,子句會篩選掉所有數位,但小於五的數位除外。 如果您移除 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

範例 2

在單 where 一子句中,您可以使用 && 和|| 運算符,視需要指定多個述詞。 在下列範例中,查詢會指定兩個述詞,以便只選取小於五的偶數。

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

範例 3

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

備註

where 句是篩選機制。 它幾乎可以放置在查詢表達式中的任何位置,但不能是第一個或最後一個子句。 where子句可能會在群組子句之前或之後出現,視您必須在群組之前或之後篩選來源元素而定。

如果指定的述詞對數據源中的專案無效,編譯時期錯誤將會產生。 這是 LINQ 所提供的強型別檢查的其中一個優點。

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

另請參閱