System.Predicate<T> 委托
表示定义一组条件并确定指定对象是否符合这些条件的方法
这是微软官方的定义
public delegate bool Predicate<T>( T obj )
类型参数
T
要比较的对象的类型。
我的例子:参数
obj
- 类型:T 要按照由此委托表示的方法中定义的条件进行比较的对象。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace languageDemo
{
public class lamdba
{
public List<People> Peoples { get; set; }
public People GetSomeOne()
{
return Peoples.Find(AgeBigThen3);
}
private bool AgeBigThen3(People people)
{
if (people.Age > 3)
{ return true; }
else
{return false;}
}
}
public class People
{
public int Id { get; set; }
public string Name{get;set;}
public int Age{get;set;}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace languageDemo
{
class Program
{
static void Main(string[] args)
{
lamdba lamda = new lamdba();
lamda.Peoples = new List<People>(){
new People(){ Age=1, Id=1,Name="wxp"},
new People(){ Age=2, Id=2,Name="wxp1"},
new People(){ Age=3, Id=3,Name="wxp2"},
new People(){ Age=4, Id=4,Name="wxp3"},
};
People wxp= lamda.GetSomeOne();
}
}
}
调试之后发现Find的执行顺序是循环遍历该列表,找到第一个满足条件的类后跳出,
通过我们自己实现也是可以的他只不过封装了下,
本文介绍了C#中Predicate委托的使用方法,并通过一个具体的示例展示了如何利用Predicate委托配合List<T>.Find方法来查找满足特定条件的对象。
1440

被折叠的 条评论
为什么被折叠?



