數量值作業會傳回值 Boolean ,指出序列中的部分或所有專案是否符合條件。
這很重要
這些範例會使用 System.Collections.Generic.IEnumerable<T> 資料來源。 根據 System.Linq.IQueryProvider 的資料來源會使用 System.Linq.IQueryable<T> 資料來源和運算式樹。 運算式樹在允許的 C# 語法方面有限制。 此外,每個 IQueryProvider
資料來源 (例如 EF Core) 可能會施加更多限制。 檢查資料來源的文件。
下圖描繪在兩個不同的來源序列上進行的兩種不同量詞運算。 第一個作業會詢問任何元素是否為字元 『A』。 第二個作業會詢問所有元素是否都是字元 『A』。 這兩種方法都會在此範例中傳回 true
。
方法名稱 | 說明 | 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