Lambda expressions Basics

Source: Internet
Author: User

Lambda expressions Basics
I. Introduction

A Lambda Expression is an anonymous function that contains several expressions and statements. Can be used to create a delegate object or expression tree type. Lambda expressions are particularly useful for writing a LINQ query expression.

All Lambda expressions use the operator "=>" to represent "goes )". The left part of the operator is the input parameter table, and the right part is the expression or statement block. Next, let's take a look at its functions and usage.

Ii. When to use it?

Before Framework 2.0, the only way to declare a delegate is to name it by using methods. From Framework 2.0, the system supports anonymous methods.
By using the anonymous method, you can directly bind a piece of code to an event, thus reducing the coding system overhead required to instantiate the delegate.
In Framework 3.0, Lambda expressions gradually replace anonymous methods as the preferred method for writing Inline code. In general, Lambda expressions are used to write anonymous methods in a simpler way and completely simplify the use of delegation.

Let's take a look at several instances!

Use the anonymous method

Static void Main (string [] args)

 

{

 

Button btn = new Button ();

 

Btn. Click + = delegate (objectobj, EventArgs e ){

 

MessageBox. Show ("HelloWorld! ");

 

};

 

}

 

Use Lambda expressions
<span style="font-size:18px;">static void Main(string[] args)         {             Button btn = new Button();             btn.Click+=(object obj,EventArgs e)=>{                 MessageBox.Show("Hello World !");             };         } </span>


Through the above practices on anonymous functions and Lambda expressions, do you find that Lambda expressions are actually an anonymous function, but they are easier to understand and simpler than anonymous functions, this is also the reason for its rapid development in recent years! Next we will explain the Lambda expressions.

Iii. Expression usage 1. Expression Lambda

A Lambda expression composed of a computing expression is calledExpressionLambda. Expression Lambda is often used to construct an Expression Tree. A Lambda expression returns the result of the computation expression.

Basic Structure:

(Input parameters) => expression

If there is only one input parameter, parentheses can be omitted. If more than one input parameter exists, brackets must be added.

(X) => x * x equals x => x * x

(X, y) => x = y

You can explicitly specify the type of the input parameter

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

You can also leave no input parameters

() => SomeMethod1 ()

The above code calls a method in Lambda. It should be noted that when creating an Expression Tree that will be used by others, it is not appropriate to execute method calls in Lambda. For example, execute in SQL Server.

In general, it is meaningless or impossible to let a method be executed outside the originally designed context environment.

2. Statement Lambda

Statement LambdaIt is very similar to the expression Lambda, but the statement is included in braces:

(Input parameters) =>{ statement ;}

The statements in braces can be any number of rows or multiple rows (define a Lambda statement that defines an anonymous method ):

TestDelegate myDel = n => {string s = n + "" + "World ";

Console. WriteLine (s );};

Of course, statements Lambda, like anonymous methods, cannot be used to create expression trees.

3. Type Prediction

When writing a Lambda statement, we usually do not need to specify the type of the input parameter. The compiler guesses the type based on The Implementation of The Lambda body and the definition of the delegate.

For example, if you want to delete an element smaller than 100 from a List <int>

Llst. RemoveAll (I => I <100 );// I will be guessed as int

The general rules are as follows:

1.Lambda must contain the same number of input parameters as the delegate definition;

2.Each Lambda input parameter must be implicitly converted to the input parameter required in the delegate definition;

3. The Lambda return value must be implicitly converted to the return value in the delegate definition.

Note: Currently, there is no "Lambda type" type in the common type system. If "Lambda type" is mentioned in some cases, it usually indicates the delegate definition or Expression <> type.

4. variable scope in Lambda

External variables can be referenced in Lambda definitions. Any variables that can be accessed at the definition can be referenced in Lambda.

A Lambda definition defines an anonymous method and generates a delegate object. The reference of external variables will be "captured" inside the delegate object, and will be accompanied by the entire life cycle of the delegate object. This variable will not be garbage collected until the life cycle of the delegate object ends. Even if the external variables have exceeded the original scope, they can still be used in Lambda. All referenced external variables must be explicitly assigned values before Lambda definitions. See the following example.

Delegatebool D ();

Delegatebool D2 (int I );

ClassTest

{

Ddel;

D2del2;

Publicvoid TestMethod (int input)

{

Intj = 0;

// Initialize the delegates with lambda expressions.

// Note access to 2 outer variables.

// Del will be invoked within this method.

Del = () => {j = 10;Return j> input ;};

// Del2 will be invoked after TestMethod goes out of scope.

Del2 = (x) => {return x = j ;};

// Demonstrate value of j:

// Output: j = 0

// The delegate has not been invoked yet.

Console. WriteLine ("j = {0}", j );

// Invoke the delegate.

BoolboolResult = del ();

// Output: j = 10 B = True//Note that jIs modified during execution

Console. WriteLine ("j = {0}. B = {1}", j, boolResult );

}

Staticvoid Main ()

{

Testtest = new Test ();

Test. TestMethod (5 );

// Prove that del2 still has a copy

// Local variable j from TestMethod. // the reference of j exceeds the scope defined previously.

Boolresult = test. del2 (10 );

// Output: True

Console. WriteLine (result );

Console. ReadKey ();

}

}

The following are the rules on variable scope:

1. variables that are "captured" will not be reclaimed before the end of the Delegate's lifecycle;

2. variables defined in Lambda are invisible to the outside world;

3.Lambda cannot directly capture a parameter variable with ref or out descriptions;

4. The return statement in Lambda does not cause the current method to return;

5. The Lambda statement cannot contain the goto, break, or continue statements that will cause the current execution range to jump.

Iv. Summary

Lambda is another form of anonymous method. It can be used in some places to make the code more concise. Defining a Lambda is essentially defining the implementation body of a delegate.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.