此委托返回一个bool值,该委托通常引用一个"判断条件函数"。需要指出的是,判断条件一般为“外部的硬性条件”,比如“大于50”,而不是由数据自身指定,不如“查找数组中最大的元素就不适合”。
例一
- class Program
- {
- bool IsGreaterThan50(int i)
- {
- if (i > 50)
- return true;
- else
- return false;
- }
- static void Main(string[] args)
- {
- Program p=new Program();
- List<int> lstInt = new List<int>();
- lstInt.Add(50);
- lstInt.Add(80);
- lstInt.Add(90);
- Predicate<int> pred = p.IsGreaterThan50;
- int i = lstInt.Find(pred); // 找到匹配的第一个元素,此处为80
- Console.WriteLine("大于50的第一个元素为{0}",i);
- List<int> all = lstInt.FindAll(pred);
- for (int j = 0; j < all.Count(); j++)
- {
- Console.WriteLine("大于50的数组中元素为{0}", all[j]); // 找出所有匹配条件的
- }
- Console.ReadLine();
- }
- }
例二
- class Staff
- {
- private double salary;
- public double Salary
- {
- get { return salary; }
- set { salary = value; }
- }
- private string num;
- public string Num
- {
- get { return num; }
- set { num = value; }
- }
- public override string ToString()
- {
- return "Num......" + num + "......" + "......" + "Salary......" + salary;
- }
- }
- class Program
- {
- bool IsSalaryGreaterThan5000(Staff s)
- {
- if (s.Salary > 5000)
- return true;
- else
- return false;
- }
- static void Main(string[] args)
- {
- Program p = new Program();
- List<Staff> allStaff = new List<Staff>
- {
- new Staff{Num="001",Salary=9999.9},
- new Staff{Num="002",Salary=8991},
- new Staff{Num="003",Salary=10000.8},
- new Staff{Num="004",Salary=4999.99}
- };
- Predicate<Staff> s = p.IsSalaryGreaterThan5000;
- Staff theFirstOne = allStaff.Find(s);
- Console.WriteLine(theFirstOne); // 找出第一个
- List<Staff> all = allStaff.FindAll(s);
- for (int i = 0; i < all.Count(); i++)
- {
- Console.WriteLine(all[i]); // 找出所有满足条件的
- }
- Console.ReadLine();
- }
- }
- 转自:http://blog.csdn.net/woshixuye/article/details/8228258