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

Source: Internet
Author: User

C # Lambda expressions and the creation of the Lambda Expression Tree
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 expressions" are anonymous functions and are efficient expressions similar to functional programming. 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): copy the code using System. linq. expressions; namespace ConsoleApplication1 {class Program {static void Main (string [] args) {Expression <del> myET = x => x * x ;}}} copy Code 1. The Lambda expression at the right of the => operator is called "expression lambda ". Expression lambda returns the expression result in the following basic form: (input parameters) => expression is 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, it is difficult for the compiler to or cannot 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 null parentheses to specify zero input parameters: () => SomeMethod () 2. Statement Lambda when there are multiple statements in the lambda expression, the statement is written as follows: (input parameters) =>{ statement;} example: delegate void TestDelegate (string s );... TestDelegate myDel = n => {string s = n + "" + "World"; Console. writeLine (s) ;}; myDel ("Hello"); now, the basic knowledge of Lambda has been learned. The following describes how to use it in practice, here are a few examples: copy the code List <string> Citys = new List <string> () {"BeiJing", "ShangHai", "Tianjin", "GuangDong "}; var result = Citys. first (c => c. length> 7); copy the Code. This is a familiar LINQ statement. It doesn't matter if you haven't learned it. Here we use only 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 ourselves, we also need to write the loop traversal set, then, judge whether the length of the string is greater than 7. At least four or five lines of code should be written. Here, only one line is enough, and LINQ also needs to be written for a long time. Here we use the simplest Lambda expression (input parameters) => expression form. Next, let's take a look at how to define and use Lambda expressions. 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 nothing, but calls the delegate method, and pass the parameter over. Next let's take a look at the usage: copy the code LambdaFun ("BeiJing 2013", s => {if (s. contains ("2013") {s = s. replace ("2013", "2014") ;}return s ;}); copy the code here to Replace 2013 in the input string with 2014, of course, it can also be to replace any content of other strings, or intercept, connect, etc. It is entirely determined by the Lambda expression we passed in. Here we feel the Lambda table It's amazing. Lambda Expression Tree dynamic creation method copy code 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> lambda = Expression. lambda <Func <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> 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 ();}

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.