C # Lambda expressions and the creation of the lambda Expression Tree

Source: Internet
Author: User
 

Recently, due to project requirements, I have just completed the action delegate and func <t> delegate. after learning the delegate, I have to learn the lambda expression and combine the delegate with the lambda expression, in order to fully reflect the convenience of delegation, in order to make the code more concise and elegant.

 

 

 

Lambda expressions

 

"Lambda expression" is an anonymous function and an efficient function-like programming expression. Lambda simplifies the amount of code to be written during development. It can contain expressions and statements and can be used to create a delegate or expression directory tree type. It supports inline expressions with input parameters that can be bound to the delegate or Expression Tree. All lambda expressions use the lambda operator =>, which is read as "goes ". The left side of the lambda operator is the input parameter (if any), and the right side is the expression or statement block. Lambda expressions x => X * x read as "X goes to X times X ". You can assign this expression to the 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 the expression directory tree type (detailed description later ):

using System.Linq.Expressions;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            Expression<del> myET = x => x * x;        }    }}
  

1. Expression Lambda

 

The Lambda expression at the right of the => operator is called "expression Lambda ". Lambda returns the result of the expression in the following basic form:

 
       (input parameters) => expression
 

Parentheses are optional only when Lambda has only one input parameter; otherwise, parentheses are required. Two or more input parameters in parentheses are separated by commas:

 
(x, y) => x == y
 

Sometimes, the compiler is difficult or unable to infer the input type. In this case, you can explicitly specify the type as shown in the following example:

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

Use parentheses to specify zero input parameters:

 
() => SomeMethod()

2. Statement Lambda

When a Lambda expression contains multiple statements, it is written as follows:

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

delegate void TestDelegate(string s);…TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };myDel("Hello");

 

Here, the basic knowledge of Lambda has been learned, and the following describes how to use it. Here are several small examples:

            List<string> Citys= new List<string>()            {               "BeiJing",               "ShangHai",               "Tianjin",               "GuangDong"            };            var result = Citys.First(c => c.Length > 7);

This is a familiar LINQ statement. If you haven't learned it, it doesn't matter. Here we use just a few simple methods. I believe everyone can understand it.

First, define a citys set and initialize some data. Then call the first method of LINQ to query the first result with a length greater than 7. Now, we can see that the lambda expression is used here,

If we write it on our own, we also need to write a loop traversal set, and then judge whether the string length is greater than 7. At least four or five lines of code should be written, and only one line is enough here, and the writing of LINQ is also very long.

Here we use the simplest Lambda expression (input parameters) => Expression form.

 

Let's take a look at how to define and use lambda expressions by yourself. First, write the following function:

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

The func <t> delegate is used here. If you do not understand it, you can go to Baidu to check the information. This method does not do anything, but calls the delegate method and passes the parameter over, let's take a look at the usage:

   LambdaFun("BeiJing 2013", s =>          {            if (s.Contains("2013"))            {               s = s.Replace("2013", "2014");            }            return s;         });

Here, we replace 2013 in the input string with 2014. Of course, we can also replace any content in other strings, or intercept, connect, and so on. It is entirely determined by the lambda expression we passed in, now, I feel that Lambda expressions are powerful.

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 the Expression Tree. As a node, parameterexpression B = expression is the lowest node. parameter (typeof (INT), "J"); binaryexpression R1 = expression. multiply (a, B); // here I * j, generate a node in the expression tree, a higher level parameterexpression c = expression than the above node. parameter (typeof (INT), "W"); parameterexpression d = expression. parameter (typeof (INT), "x"); binaryexpression r2 = expression. multiply (c, d); binaryexpression result = expression. add (R1, R2); // calculates two intermediate nodes and generates an end point expression <func <int, Int, int> Lambda = expression. lambda <func <int, Int, int> (result, A, B, C, D); console. writeline (lambda + ""); // output '(I, j, w, x) => (I * j) + (w * X ))', Z corresponds to parameter B and parameter P corresponds to parameter a func <int, Int, Int, int> F = lambda. compile (); // compile the lambda expression described in the expression tree into executable code and generate the delegate of the lambda expression. console. writeline (f (1, 1, 1, 1) + ""); // output result 2 console. readkey ();}

To facilitate your understanding, the lambda Expression Tree composed of this Code is as follows:

In fact, lambda expressions are not difficult. Only by understanding the principles can we get started quickly!

 

C # Lambda expressions and the creation of the 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.