A detailed description of C # lambda expressions, and the creation of a lambda expression tree

Source: Internet
Author: User

  Recently because of the project needs, just finished learning the action delegate and Func<t> delegate, found that after learning the delegate must learn the lambda expression, the delegation and the lambda expression together, in order to fully reflect the convenience of the delegate, in order to make the code more brief, elegant.

Lambda expression

A lambda expression is an anonymous function, an efficient expression similar to functional programming, and lambda simplifies the amount of code that needs to be written in development. It can contain expressions and statements, and can be used to create delegates or expression tree types, and supports inline expressions with input parameters that can be bound to delegates or expression trees. All lambda expressions use the lambda operator =>, and the operator reads "goes to". The left side of the lambda operator is the input parameter (if any), and the right is the expression or statement block. The lambda expression x + x * x is read as "x goes to X times X". You can assign this expression to a delegate type, as follows:

delegate int del (int i); static void Main (string[] args) {    del mydelegate = x = x * x;    Int J = MyDelegate (5); j = 25}

To create an expression tree type (detailed later):

Using System.linq.expressions;namespace consoleapplication1{    class program    {        static void Main (string[] args)        {            expression<del> myet = x = * x * x;}}    }

1. Expression Lambda

expression lambda. " The lambda expression on the right side of the + = operator is called expression Lambda. expression lambda. " >expression Trees (C # and Visual Basic). >  expression lambda returns the result of the expression and takes the following basic form:

       (input parameters) = Expression

Parentheses are optional only if the lambda has only one input parameter, otherwise parentheses are required. two or more input parameters in parentheses are delimited by commas:

(x, y) = x = = Y

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

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

Specify 0 input parameters with an empty parenthesis:

() = SomeMethod ()

2. Statement Lambda

When there are multiple statements in a lambda expression, the following form is written:

(input parameters) = {statement;}
For example:

delegate void Testdelegate (string s); .... Testdelegate Mydel = n = {string s = n + "" + "world"; Console.WriteLine (s); };mydel ("Hello");

See here, the basic knowledge of Lambda is finished, below to explain how to use the actual, here are a few small examples:

            list<string> citys= New list<string> ()            {               "Beijing",               "Shanghai",               "Tianjin",               " Guangdong "            };            var result = Citys.first (c = c.length > 7);

This is familiar with the LINQ statement, if you have not learned it's OK, here is just a few simple methods, I believe we can read.

First define a Citys collection and initialize some data. And then call the first method of LINQ, and query out a result of a length greater than 7, see, here is the lambda expression,

If we write ourselves, we also write loops to iterate through the collection, and then determine if the string length is greater than 7, at least write four or five lines of code, where only one line is enough, and LINQ has to write very long.

Here is the simplest lambda expression, (input parameters) and the form of expression.

Here's a look at how to define and use a lambda expression yourself, first write the following function:

    public void Lambdafun (String str,func<string,string> Func)      {         Console.WriteLine (func (str));      }

Here to use the func<t> commissioned, do not know can go to Baidu to check the information, this method did nothing, just call the delegate method, and pass the parameters passed, the following to see how to use:

   Lambdafun ("Beijing", s +          = {            if (s.contains (")")            {               s = s.replace ("n");            }            return s;         });

This will replace 2013 of the passed in string into 2014, of course, it can also be the substitution of any other string in the city, or interception, connection, and so on, completely determined by our incoming lambda expression, and here we feel the power of lambda expression.

Lambda expression tree Dynamic creation method  
     static void Main (string[] args) {//i*j+w*x parameterexpression a = Expression.parameter   (typeof (int), "I");            Create a parameter in an expression tree, as a node, here is the lowest node parameterexpression b = Expression.parameter (typeof (int), "J");    binaryexpression r1 = Expression.multiply (A, b);            Here i*j, generate a node in the expression tree, higher than the above node parameterexpression C = Expression.parameter (typeof (int), "w");            ParameterExpression d = expression.parameter (typeof (int), "x");            binaryexpression r2 = expression.multiply (c, D);   Binaryexpression result = Expression.add (R1,R2); Operations two intermediate nodes, resulting in endpoint expression<func<int, int, int, int, int>> lambda = expression.lambda<func<in            t, int, int, int, int>> (result,a,b,c,d);   Console.WriteLine (lambda + "");  Output ' (i,j,w,x) = ((i*j) + (w*x)) ', z corresponding parameter b,p corresponding parameter a func<int, int, int, int, int> f= lambda.compile ();          The lambda expression described by the expression tree is compiled into executable code and the delegate of the lambda expression is generated;  Console.WriteLine (f (1, 1, 1, 1) + "");        Output result 2 console.readkey (); }

To make it easy to understand, this code consists of a lambda expression tree such as:

In fact, lambda expression is not difficult, only understand the principle, or quickly can get started!

A detailed description of C # lambda expressions, and the creation of a lambda expression tree

Related Article

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.