Lambda表达式

一、定义
Lambda 表达式是一种可用于创建 委托 或 表达式目录树 类型的 匿名函数 。通过使用 lambda 表达式,可以写入可作为参数传递或作为函数调用值返回的本地函数。(微软)
理解
1.Lambda表达式是一种匿名方法。
匿名方法可省略参数列表,Lambda表达式不能省略参数列表的圆括号()
//只需要使用一个delegate关键字,加上作为方法的操作使用的代码块。
Action printer = delegate { Console.WriteLine(“Hello world”); };
printer();
//一个没有参数的方法,返回值的类型不用指定 系统会自动判断
() => Console.WriteLine()
二、发展
委托 → 匿名方法 → lambda表达式 → 泛型委托 → 表达式树
//委托分3步
//step01:用delegate定义一个委托
public delegate int deleFun(int x,int y);
//step02:声明一个方法来对应委托
public static int Add(int x, int y)
{
return x + y;
}
static void Main(string[] args)
{
//step03:用这个方法来实例化这个委托
deleFun dFun = new deleFun(Add);
Console.WriteLine(dFun.Invoke(5, 6));
}
//匿名方法分2步
//step01:用delegate定义一个委托
public delegate int deleFun(int x,int y);
static void Main(string[] args)
{
//step02:把一个方法赋值给委托
deleFun dFun = delegate(int x, int y) { return x + y; };
Console.WriteLine(dFun.Invoke(5, 6));
}
//lambda表达式简化了第2步
//step01:用delegate定义一个委托
public delegate int deleFun(int x,int y);

static void Main(string[] args)
{
//step02:把一个方法赋值给委托
deleFun dFun = (x, y) => {return x + y; };
Console.WriteLine(dFun.Invoke(5, 6));
}
//泛型委托只需要1步
static void Main(string[] args)
{
//step01:定义泛型委托 并把一个方法赋值给委托
Func<int, int, int> dFun = (x, y) => { return x + y; };
Console.WriteLine(dFun.Invoke(5, 6));
}
说明
在 C# 2.0 中引入了泛型。现在我们能够编写泛型类、泛型方法和最重要的:泛型委托。
• Action :无输入参数,无返回值
• Action<T1, …, T16> :支持1-16个输入参数,无返回值
• Func<T1, …, T16, Tout> :支持1-16个输入参数,有返回值
//表达式树其实与委托已经没什么关系了,非要扯上关系,那就这么说吧,表达式树是存放委托的容器。
//如果非要说的更专业一些,表达式树是存取Lambda表达式的一种数据结构。要用Lambda表达式的时候,直接从表达式中获取出来,Compile()就可以直接用了。

static void Main(string[] args)
{
Expression<Func<int, int, int>> exp = (x, y) => x + y;
Func<int, int, int> fun = exp.Compile();
Console.WriteLine(fun.Invoke(5, 6));
}
when
1、列表迭代
List numbers = new List() { 1, 2, 3 };

//一般用法
foreach (int i in numbers)
Console.WriteLine(i);

//使用lambda
numbers.ForEach(i => Console.WriteLine(i));
2、linq 和lambda
//linq
var students1 = from t in db.Students
where t.Name == “张三”
select new { t.Id, t.Name, t.Age };

//lambda
var students2 = db.Students
.Where(t => t.Name == “张三”)
.Select(t => new { t.Id, t.Name, t.Age });
参考自别人的博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值