Predicate泛型委托:表示定義一組條件并確定指定對象是否符合這些條件的方法。此委托由 Array 和 List 類的幾種方法使用,用于在集合中搜索元素。 Predicate<T>
通常用于集合的篩選或搜索操作,比如在 List<T>
的 Find
或 Exists
方法中使用。
常見用法
在列表中查找元素:
可以使用 Predicate<T>
在集合中查找符合特定條件的元素。
using System;
using System.Collections.Generic;
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// 使用 Predicate 查找第一個偶數
Predicate<int> isEven = num => num % 2 == 0;
// 查找第一個偶數
int evenNumber = numbers.Find(isEven);
Console.WriteLine("第一個偶數是: " + evenNumber);
輸出:
第一個偶數是: 2
檢查列表中是否存在某個元素:
Predicate<T>
可以用來檢查集合中是否有元素滿足特定的條件。
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// 使用 Predicate 判斷是否有大于 5 的數字
Predicate<int> isGreaterThanFive = num => num > 5;
// 檢查是否存在符合條件的數字
bool exists = numbers.Exists(isGreaterThanFive);
Console.WriteLine("是否有大于 5 的數字? " + exists);
輸出:
是否有大于 5 的數字? True
與 List<T>.RemoveAll
一起使用:
Predicate<T>
可以用來從集合中刪除滿足某個條件的元素。
using System;
using System.Collections.Generic;
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// 使用 Predicate 刪除所有偶數
Predicate<int> isEven = num => num % 2 == 0;
// 刪除所有偶數
numbers.RemoveAll(isEven);
Console.WriteLine("刪除偶數后的剩余數字:");
foreach (var num in numbers)
{
Console.WriteLine(num);
}
輸出:
刪除偶數后的剩余數字:
1
3
5
7
9
使用 Lambda 表達式和 Predicate
可以通過 lambda 表達式來簡潔地定義一個 Predicate<T>
,如上面示例中的 num => num % 2 == 0
。
總結
- ?
Predicate<T>
是一個委托類型,它接受一個類型為 T
的參數并返回一個布爾值。 - ? 它常用于對集合進行篩選、查找或者驗證元素是否滿足特定條件。
- ?
List<T>
類中有如 Find
、Exists
和 RemoveAll
等方法可以接受 Predicate<T>
,用于對集合進行操作。
閱讀原文:原文鏈接
該文章在 2025/4/8 8:39:17 編輯過