C # lambda expression

Source: Internet
Author: User

Lambda expression

Preface: We can use a new syntax to assign the implemented code to a delegate: a lambda expression. A lambda expression can be used wherever there is a delegate parameter type. We changed the example from our last blog to a lambda expression.

The complete code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespace_15 anonymous Method {classProgram {Static voidMain (string[] args) {            stringMID =", I was in the middle,"; Func<string,string> lambda = param + ={param+=mid; Param+="I'm the last one."; returnparam;            }; Console.WriteLine (Lambda ("I'm on the front."));        Console.readkey (); }    }}

The code is displayed as follows:

Lambda expressions have several ways to define parameters. The left side of "= =" Lists the required parameters, and the right side of the lambda operator defines the code that implements the method that gives the lambda variable.

One: Parameters:

Lambda expressions have several ways of defining parameters, and if you have only one argument, just write the parameter name. The following lambda expression uses the parameter S. Because the delegate defines a string parameter, the type of S is the string type. Implement code call String.Format (); method to return a string that is written to the console when the delegate is called.

func< astringstring string. Format (" converted to uppercase form: {0}", S.toupper ()); Console.WriteLine (Oneparam ("hao"));

As follows:

If you use multiple parameters, place the parameter names in curly brackets, where the parameters x and Y are double types, defined by the Func<double,double,double> delegate:

Private Static func<Doubledouble double > _twoparams = (x, y) + x * y;

Method is called:

Console.WriteLine (_twoparams (32));

We can not add the type of the parameter in the curly braces, because the compiler will automatically help us match the type of the parameter.

Two: Multiple lines of code:

If there is only one statement in the lambda expression, no curly braces and return statements are required within the method block, because the compiler adds an implicit return statement. For example, let's look at the following line of code:

Private Static func<doubledouble> squate = x = x * x;

But adding or parentheses and return statements are perfectly legal, but adding these symbols is not easy to read and is added as follows:

Private Static func<doubledoublereturn x * x; };

However, if you want to implement multiple statements in a lambda expression, you must add curly braces and return.

           func<stringstring> Anondel =                param = + = mid;                 " And this is added to the string " ;                 return param;            };

Three: Closures:

A lambda expression provides access to variables outside the lambda expression. This is called closures. closures are a very good feature, but if used improperly, it can be very dangerous, first we look at an example:

int 5 ; Func<intint> f = x = x + someval;

Assuming that the lambda expression creates a new method to be used later when you call F, it doesn't seem to be a problem, let's look at the code we wrote above, the return value of the call F should be the result of x+5. But that doesn't seem to be the case, assuming we want to modify the Someval, and then invoke the lambda expression, the new value of Someval is used. The result of calling F (3) is 10;

In particular, when a lambda expression is invoked through another thread, we may not know that the call was made, and we do not know what the current value of the external variable is. That our lambda expression when accessing variables outside, for lambda:x=>x + Someval, the compiler creates an anonymous class that has a constructor to pass external variables. The constructor depends on the number of variables passed in from the outside. For this simple example. The constructor receives an int. The anonymous class contains an anonymous method. The complete code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespace_16lambda Expression {/// <summary>    ///Anonymous Class/// </summary>     Public classAnonymousclass {Private int_someval;  Public intSomeval {Get{return_someval;} Set{_someval =value;} }        /// <summary>        ///constructor Initialization assignment Operation/// </summary>        /// <param name= "Someval" >externally passed values</param>         PublicAnonymousclass (intsomeval) {             This. Someval =Someval; }        /// <summary>        ///Anonymous Methods/// </summary>        /// <param name= "x" ></param>        /// <returns></returns>         Public intAnonymousmathod (intx) {returnX +_someval; }    }}

Using a lambda expression and calling the method creates an instance of an anonymous class and passes the variable when the method is called.

Four: Closures using the foreach statement:

Let's look at the code first:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Security.Cryptography.X509Certificates;usingSystem.Text;usingSystem.Threading.Tasks;namespace_16lambda Expression {classProgram {Static voidMain (string[] args) {            //Generic Collectionlist<int> values =Newlist<int> () {Ten, -, - }; //method of storing a delegate type in a generic collection (with no parameters for return values)list<func<int>> Funcs =Newlist<func<int>>(); //traversing values stored in the collection//The object added in the collection is not a parameter but returns each value in the values collection            foreach(varValinchvalues) {Funcs. Add (()=val); }            //Traverse Collection Delete all methods F (): No parameter has a value of type int            foreach(varFinchFuncs)            {Console.WriteLine (f ());        } console.readkey (); }    }}

In the example above, a list named values is first populated with 10 20 30, and the variable Funcs refers to a generic list in which each object references a delegate of type func<int>. The first foreach statement adds each element in the Funcs list. Functions added to an item are defined using a lambda expression. The lambda expression uses a variable Val, which is defined outside the lambda expression as a loop variable of the foreach statement. The second foreach statement iterates through the Func list, calling each function referenced in the list. The results are as follows:

In c#5.0, this code changes, but when using C#4 or earlier versions, it outputs 3 times in the console 30, when the first foreach Loop China uses the closure, the function that is created is in the call, not in the iteration, to get Val value. The compiler creates a while loop from the foreach language. In C#4, the compiler defines a loop variable outside the while loop. This variable is reused in each iteration. Therefore, at the end of the loop, the value of the variable is the value of the last iteration. To make the code result 10 20 30 when using C#4, you must change the code to use a local variable. and pass this local variable into the lambda expression. In this case, the value of each iteration retains a different value. The complete code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Security.Cryptography.X509Certificates;usingSystem.Text;usingSystem.Threading.Tasks;namespace_16lambda Expression {classProgram {Static voidMain (string[] args) {            //Generic Collectionlist<int> values =Newlist<int> () {Ten, -, - }; //method of storing a delegate type in a generic collection (with no parameters for return values)list<func<int>> Funcs =Newlist<func<int>>(); //traversing values stored in the collection//The object added in the collection is not a parameter but returns each value in the values collection            foreach(varValinchvalues) {                varv =Val; Funcs. Add (()=v); }            //Traverse Collection Delete all methods F (): No parameter has an int type            foreach(varFinchFuncs)            {Console.WriteLine (f ());        } console.readkey (); }    }}

In c#5.0, it is not necessary to make this kind of code modification (the variable that changes the code to local). The c#5.0 creates a different local loop variable in the code block of the while loop. So the value will be saved automatically. This is the difference between c#4.0 and c#5.0, which is what we have to know.

C # lambda expression

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.