分类: C#

Understand Lambda Expressions






What is a Lambda Expression?

A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.

(In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code)

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

Convenience. It’s a shorthand that allows you to write a 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.

Benefits:

  • Reduced typing. No need to specify the name of the function, its return type, and its access modifier.
  • When reading the code you don’t need to look elsewhere for the method’s definition.

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

Where do we use lambda expression?

lambdas can only be used where delegates (pointing to a function somewhere else) are required.

like example below, method request delegate function return:

delegate_capture

How do we define a lambda expression? 

Lambda basic definition: Parameters => Executed code.

Same example

n => n % 2 == 1
/* n is the input parameter
n % 2 == 1 is the expression*/

You can read n => n % 2 == 1 like: “input parameter named n goes to anonymous function which returns true if the input is odd“.


List<int> numbers = new List<int>{11,37,52};

List<int> oddNumbers = numbers.where(n => n % 2 == 1).ToList();

//Now oddNumbers is equal to 11 and 37

The parentheses are optional only if the lambda has one input parameter; otherwise they are required. Two or more input parameters are separated by commas enclosed in parentheses:


(x, y) => x == y

Sometimes it is difficult or impossible for the compiler to infer the input types. When this occurs, you can specify the types explicitly as shown in the following example:


(int x, string s) => s.Length > x

Specify zero input parameters with empty parentheses:


() => SomeMethod()

for more  Real-World Examples, you can refer to:

Reference :




发表评论