Lambda Expression Learning Note (1)-a lambda expression as a delegate

Source: Internet
Author: User

A lambda expression in C # is the evolution of an anonymous method in C # 2, so you start by simplifying the way you do it from an anonymous function.

The example is to get a string parameter and then return an int.

First, the anonymous method is written as follows:

Func<string, int> returnlength;            Returnlength = Delegate (string text) {return text. Length; };            Console.Write (Returnlength ("Hello"));

The most verbose form of a lambda expression is:

(Explicit type argument list) = = {statement} (= = can be seen as goes to)

The above example LANBDA expression can be written as:

            Func<string, int> returnlength;            Returnlength = (string text) = = {return text. Length; };            Console.Write (Returnlength ("Hello"));            Console.read ();     

This notation is very similar to the anonymous method

In addition to returning a value in the form of a block of code, most of the time an expression is used to represent the entire body, and the value of the expression is the result of the lambda, and the format becomes:

(explicit argument list) = = Expression

The above example becomes

            Func<string, int> returnlength;            Returnlength = (string text) = = text. Length;    

Because the compiler is strong enough to be able to easily guess the type of the parameter, in this case it can be further simplified to:

(Implicitly typed argument list) = = Expression

The above example becomes:

            Func<string, int> returnlength;            Returnlength = (Text) = = text. Length;

So far it's quite brief, but in the case of a parameter, this parenthesis is a bit of an eyesore, so you can continue to simplify:

Parameter name-= Expression

The final form of the lambda expression for an example is:

            Func<string, int> returnlength;            Returnlength = text + text. Length;        

  

Lambda Expression Learning Note (1)-a lambda expression as 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.