Predicate在集合搜尋和WPF資料繫結中用途廣泛,其調用形式:
調用形式:Predicate<object>(Method)/Predicate<參數類型>(方法)
1.<>表示泛型,可以接受任何類型的參數
2.(Method)可以接受方法為參數進行傳遞,表示一個委託
3.傳回型別為bool型,表示成功與否
一個例子,在empList中尋找特定項:
class Employee{ private string _firstName; private string _lastName; //private int _empCode; private string _designation; public Employee() { } public Employee(string firstName, string lastName, string designation) { _firstName = firstName; _lastName = lastName; _designation = designation; } /// <summary> /// Property First Name /// </summary> public string FirstName { get { return _firstName; } set { _firstName = value; } } /// <summary> /// Property Last Name /// </summary> public string LastName { get { return _lastName; } set { _lastName = value; } } public string Designation { get { return _designation; } set { _designation = value; } }
1.傳統方法
定義一個搜尋方法:
static bool EmpSearch(Employee emp) { if (emp.FirstName == "Anshu") return true; else return false; }
使用泛型的Find()方法,Find()內部自動迭代調用EmpSearch方法
Predicate<Employee> pred = new Predicate<Employee(EmpSearch);Employee emp = empList.Find(pred);
2.使用匿名方法
emp = empList.Find(delegate(Employee e){ if(e.FirstName == "Anshu") return true; else return false; });
不需要重新顯式的定義方法,代碼更加簡潔
3.使用lambda運算式
emp = new Employee(); emp = empList.Find((e)=> {return (e.FirstName == "Anshu");});
(e)=>表示傳遞一個參數,參數類型能夠自動解析
4.搜尋列表
List<Employee> employees = new List<Employee>();employees = empList.FindAll((e) => { return (e.FirstName.Contains("J")); });
5.搜尋索引
通過指定開始索引和搜尋條目的數量來縮小搜尋的範圍
int index = empList.FindIndex(0,2,(e) => { return (e.FirstName.Contains("J"));
表示從索引0開始,搜尋2個條目。
6.List中常用的比較子委託
給下列數組排序
var data = new List<int>();var rand = new Random();Console.WriteLine("Unsorted list");for (int i = 0; i < 10; i++){ int d =rand.Next(0,100); data.Add(d); Console.Write("{0} ",d);}
使用Lampda表示式進行從大到小排序
data.Sort((e1, e2) => {return e1.CompareTo(e2) ;});