where 句 (C# リファレンス)

where 句をクエリ式で使用して、クエリ式で返されるデータ ソースの要素を指定します。 ブール条件 (述語) を (範囲変数で参照される) 各ソース要素に適用し、指定した条件に該当するものを返します。 単一のクエリ式に複数の where 句を含めることができ、単一の句に複数の述語部分式を含めることができます。

例 1

次の例では、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

例 2

単一の where 句内には、&& および || 演算子を使用して、必要な数の述語を指定できます。 次の例のクエリでは、5 未満の偶数のみを選択するために 2 つの述語を指定します。

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 句には、ブール値を返す 1 つ以上のメソッドを含めることができます。 次の例の 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 句は、ソース要素のフィルター処理をグループ化の前に行うか後に行うかによって、group 句の前または後に指定できます。

指定した述語がデータ ソース内の要素に対して有効でない場合は、コンパイル時エラーが発生します。 これは、LINQ で提供される厳密な型チェックの 1 つの利点です。

コンパイル時に、where キーワードは Where 標準クエリ演算子メソッドの呼び出しに変換されます。

関連項目