LINQ 中的數量詞作業 (C#)
數量詞作業會傳回 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