3分钟理解lambda表达式

WHAT is a Lambda Expression?

什么是lambda表达式?

A lambda expression is an anonymous function and it is mostly used to create delegates in LINQ

一个lambda表达式就是一个匿名方法,它大多数时候在Linq中创建委托。

WHY do we need lambda expressions? (Why would we need to write a method without a name?)

为什么我们需要lambda表达式?(为什么我们需要去写一个匿名方法?)

Convenience. It's a shorthand that allows you to write method in the same place you are going to use it. Especially useful in places where a method is being used only once, and the method definition is short. It saves you the effort of declaring and writing a separate method to the containing class.

答案就是方便。lambda表达式短小精悍,在你写代码的时候需要创建一个函数,你可以用一个简短的Lambda表达式去完成这个函数,而不必要再在代码的另一段单独写一个函数块,lambda表达式维持着代码和思路的连贯性。

Lambda expressions should be short. A complex definition makes the calling code difficult to read

lambda表达式需要简洁精干,如果你写一个复杂的lambda表达式会让代码变得难以理解

HOW do we define a lambda expression?

我们怎么定义一个lambda表达式

Lambda basic definition:  Parameters => Executed code

lambda表达式的基本定义是:参数=>执行代码

举例如下:

n => n % 2 == 1 


n是输入参数,n%2==1是执行代码

再举个例子

List<int> numbers = new List<int>{11,37,52};
List<int> oddNumbers = numbers.where(n => n % 2 == 1).ToList();


相信聪明的你已经得出结果了,oddNumbers里面应该是11和37.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值