LINQ を使用した C# でのデータのフィルター処理

フィルター処理とは、特定の条件を満たす要素のみが含まれるように結果セットを限定する操作のことです。 これは、指定した条件に一致する要素の "選択" とも呼ばれます。

次の図は、文字のシーケンスをフィルター処理した結果を示したものです。 フィルター処理操作の述語では、文字が "A" でなければならないことが指定されています。

LINQ のフィルター操作を示す図。

次のテーブルでは、選択を実行する標準クエリ演算子メソッドの一覧を示します。

メソッド名 説明 C# のクエリ式の構文 説明
OfType 指定した型にキャストできるかどうかにより、値を選択します。 該当なし。 Enumerable.OfType

Queryable.OfType
Where 述語関数に基づいて値を選択します。 where Enumerable.Where

Queryable.Where

次の例では、where 句を使って、配列から特定の長さを持つ文字列をフィルター処理します。

string[] words = ["the", "quick", "brown", "fox", "jumps"];

IEnumerable<string> query = from word in words
                            where word.Length == 3
                            select word;

foreach (string str in query)
{
    Console.WriteLine(str);
}

/* This code produces the following output:

    the
    fox
*/

次のコードでは、メソッド構文を使用した同等のクエリを示しています。

string[] words = ["the", "quick", "brown", "fox", "jumps"];

IEnumerable<string> query =
    words.Where(word => word.Length == 3);

foreach (string str in query)
{
    Console.WriteLine(str);
}

/* This code produces the following output:

    the
    fox
*/

関連項目