C# Predicate委托
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) ;});
文章来自-似水无痕:http://www.cnblogs.com/keylei203/