LINQ (C#) 中的限定符运算

限定符运算返回一个 Boolean 值,该值指示序列中是否有一些元素满足条件或是否所有元素都满足条件。

下图描述了两个不同源序列上的两个不同限定符运算。 第一个运算询问是否有任何元素为字符“A”。 第二个运算询问是否所有元素都为字符“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

另请参阅