Lambda 表达式是一种可用于创建委托或表达式目录树类型的匿名函数。 通过使用 lambda 表达式,可以写入可作为参数传递或作为函数调用值返回的本地函数。在C#中的Linq中的大部分就是由扩展方法和Lambda 表达式共同来实现,如:
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector);
下面使用一个Where方法,体现委托向Lambda 表达式优化的形式:
private List<Student> students =
{
new Student() { Name = "xiaoming" },
new Student() { Name = "liufei" }
}; //第一种
public bool predicate(Student s)
{
if (s.Name == "liufei")
{
return true;
}
else
{
return false;
}
}
Func<Student, bool> t = new Func<Student, bool>(predicate);//创建委托
IEnumerable<Student> result = students.Where(t); //第二种
IEnumerable<Student> result = students.Where(delegate(Student s){
if(s.Name == "liufei")
{
return true;
}
else
{
return false;
}
}); //第三种
IEnumerable<Student> result = students.Where(s => {
if (s.Name == "liufei")
{
return true;
}
else
{
return false;
}
}); //第四种
IEnumerable<Student> result = students.Where(s => s.Name == "liufei");