次の方法で共有


LINQ での量指定子操作 (C#)

量指定子操作は、シーケンス内の一部またはすべての要素が条件を満たすかどうかを示す Boolean 値を返します。

Von Bedeutung

これらのサンプルでは、System.Collections.Generic.IEnumerable<T> データ ソースを使用します。 System.Linq.IQueryProvider に基づくデータ ソースでは、System.Linq.IQueryable<T> データ ソースと式ツリーが使用されます。 式ツリーには、許可される C# 構文に制限があります。 さらに、IQueryProvider などの各 データ ソースでは、より多くの制限が課される場合があります。 ご利用のデータ ソースのドキュメントをご覧ください。

次の図は、2 つの異なるソース シーケンスに対する 2 つの異なる量指定子操作を示しています。 最初の操作では、要素のいずれかが文字 'A' であるかどうかを確認します。 2 番目の操作では、すべての要素が文字 'A' であるかどうかを確認します。 どちらのメソッドも、この例の true を返します。

LINQ 量指定子操作

メソッド名 説明 C# のクエリ式の構文 詳細情報
全て シーケンス内のすべての要素が条件を満たすかどうかを判断します。 適用されません。 Enumerable.All
Queryable.All
[任意] シーケンス内の要素が条件を満たすかどうかを判断します。 適用されません。 Enumerable.Any
Queryable.Any
次のものを含む シーケンスに指定した要素が含まれているかどうかを判断します。 適用されません。 Enumerable.Contains
Queryable.Contains

全て

次の例では、 All を使用して、すべての試験で 70 を超えるスコアを付けた学生を見つけます。

IEnumerable<string> names = from student in students
                            where student.Scores.All(score => score > 70)
                            select $"{student.FirstName} {student.LastName}: {string.Join(", ", student.Scores.Select(s => s.ToString()))}";

foreach (string name in names)
{
    Console.WriteLine($"{name}");
}

// This code produces the following output:
//
// Cesar Garcia: 71, 86, 77, 97
// Nancy Engström: 75, 73, 78, 83
// Ifunanya Ugomma: 84, 82, 96, 80

[任意]

次の例では、 Any を使用して、どの試験でも 95 を超えるスコアを付けた学生を見つけます。

IEnumerable<string> names = from student in students
                            where student.Scores.Any(score => score > 95)
                            select $"{student.FirstName} {student.LastName}: {student.Scores.Max()}";

foreach (string name in names)
{
    Console.WriteLine($"{name}");
}

// This code produces the following output:
//
// Svetlana Omelchenko: 97
// Cesar Garcia: 97
// Debra Garcia: 96
// Ifeanacho Jamuike: 98
// Ifunanya Ugomma: 96
// Michelle Caruana: 97
// Nwanneka Ifeoma: 98
// Martina Mattsson: 96
// Anastasiya Sazonova: 96
// Jesper Jakobsson: 98
// Max Lindgren: 96

次のものを含む

次の例では、 Contains を使用して、試験で正確に 95 点を獲得した学生を見つけます。

IEnumerable<string> names = from student in students
                            where student.Scores.Contains(95)
                            select $"{student.FirstName} {student.LastName}: {string.Join(", ", student.Scores.Select(s => s.ToString()))}";

foreach (string name in names)
{
    Console.WriteLine($"{name}");
}

// This code produces the following output:
//
// Claire O'Donnell: 56, 78, 95, 95
// Donald Urquhart: 92, 90, 95, 57

こちらも参照ください