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.