限定符作返回一个 Boolean 值,该值指示序列中的某些或所有元素是否满足条件。
重要
这些示例使用 System.Collections.Generic.IEnumerable<T> 数据源。 基于System.Linq.IQueryProvider的数据源使用System.Linq.IQueryable<T> 数据源和表达式树。 表达式树对允许的 C# 语法有 限制 。 此外,每个 IQueryProvider
数据源(如 EF Core )可能会施加更多的限制。 查看数据源的文档。
下图描述了两个不同源序列上的两个不同限定符运算。 第一个操作检查是否有任何元素是字符“A”。 第二个操作是询问所有元素是否都是字符“A”。 这两种方法在此示例中都返回 true
。
方法名 | DESCRIPTION | 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