16.c# the lambda expression and expression tree (ix-9.1-9.3)

Source: Internet
Author: User

Before we describe Lambda-related knowledge, we need to understand that lambda expressions are commonly used in LINQ, so let's talk about LINQ.

The basic function of LINQ is to create operational pipelines and any state that these operations require. These operations represent a variety of logic about the data: How to filter, how to sort, and how to connect different data sources together, and so on. Executing a delegate is just one of the many capabilities of LINQ. For efficient use of databases and other query engines, we need to represent each operation in a pipeline in a different way. In this different way, you can use lambda expressions to behave. The following uses delegates (using anonymous functions) and lambda expressions, respectively, to do the same thing: return how many days a person has lived to the present.

1 class Person2 {3      PublicDateTime BirthDay {Get;Set; }4 }5 6  Public Delegate intgetlifedays (person P); //Declare a delegate type 7 Static voidMain (string[] args)8 {9Person p =NewPerson () {BirthDay =NewDateTime (1900, A, -) };Ten  OneGetlifedays GFD =Delegate(Person X) { //instantiation of a delegate
A return(DateTime.Now-x.birthday). Days; - }; - Console.WriteLine (GFD (P)); the -Getlifedays gfd1 = (Person X) + = {return(DateTime.Now-x.birthday). Days; }; - Console.WriteLine (GFD1 (P)); - +Getlifedays gfd2 = (person X) = (datetime.now-x.birthday). Days;//to remove the curly braces in the back, ";" Ends for an expression, not the end of a lambda - Console.WriteLine (GFD2 (P)); + AGetlifedays gfd3 = (x) + = {return(Datetime.now-x.birthday). Days; };//let the compiler infer the type of the parameter at Console.WriteLine (GFD3 (P)); - -Getlifedays gfd4 = (x) = = (Datetime.now-x.birthday). Days;//also omit parameter types and curly braces - Console.WriteLine (Gfd4 (P)); - -Getlifedays gfd5 = x = (datetime.now-x.birthday). Days;//further, omit the parentheses of the argument list in Console.WriteLine (GFD5 (P)); - to Console.readkey (); +}

The above is the case of a single parameter, for two or more parameters, the effect is "one to the day from birth to the number of days apart", one day must be greater than the day of birth.

1  Public Delegate intGetdaysto (person p, DateTime D);2 Static voidMain (string[] args)3 {4Person p =NewPerson () {BirthDay =NewDateTime (1900, A, -) };5 6DateTime d =NewDateTime (2100, A, A);7     //using anonymous Methods8Getdaysto GDT =Delegate(Person X, DateTime y)9     {Ten         return(Y-x.birthday). Days; One     }; A Console.WriteLine (GDT (P, D)); -  -Getdaysto gdt1 = (Person X, DateTime y) = = {return(Y-x.birthday). Days; }; the Console.WriteLine (GDT1 (P, D)); -  -Getdaysto GDT2 = (Person X, DateTime y) = = (Y-x.birthday). Days; - Console.WriteLine (GDT2 (P, D)); +  -Getdaysto GDT3 = (x, y) = = (Y-x.birthday). Days; + Console.WriteLine (GDT3 (P, D)); A  at     //Getdaysto gdt4 = x, y = = (y-x.birthday). Days; Error -     //Console.WriteLine (GDT4 (P, D)); -  - Console.readkey (); -}

It can be seen that when a parameter is two or more than two, the parentheses in the argument list cannot be omitted , which can also be imagined when the statement is above two or more than two, the curly brace cannot be omitted .

Following the previous knowledge, use the AMBDA expression on a list to manipulate it.

1 //using the collection initializer2list<person> L =NewList<person> {3     Newperson {birthday=NewDateTime (1990, One, One)},4     Newperson {birthday=NewDateTime (1890, A, A)},5     Newperson {birthday=NewDateTime (1891, A, A)},6     Newperson {birthday=NewDateTime (1892, A, A)},7     NewPerson () {birthday=NewDateTime (1870, A, A)}8 };9 Ten //find a person greater than new DateTime (1890,1,1) One varResult0 = L.findall (x = x.birthday >NewDateTime (1890,1,1)); A  - //sort by age from small to large -L.sort (x, y) = x.birthday > Y.birthday?-1:1); the foreach(varEinchl) - { -Console.WriteLine (DateTime.Now-e.birthday). days); - } +  - //cycle through the days of birth for each person, with the same effect as the above foreach +L.foreach (x = Console.WriteLine (DateTime.Now-x.birthday). Days)); A  at //people who found Birthday=new DateTime (1890,12,12) - varRESULT1 = l.find (x = = X.birthday = =NewDateTime (1890, A, A));

Next, let's say the next expression tree,. NET3.5 expressions provide an abstract way to represent some code as an object tree, and expression trees are primarily used for LINQ. The System.Linq.Expressions namespace contains classes representing expressions that are inherited from expression, an abstract class that primarily contains static factory methods that are used to create instances of other expression classes.

The expression class consists of two properties:

    1. The Type property represents an expression evaluated after the. NET type, which can be treated as a return type. For example, if an expression is to get the length of a string, the type of the expression is int.
    2. The NodeType property returns the kind of expression that is represented. It is a member of the Expressiontype enumeration.
1 Expression first = expression.constant (5); 2 Expression result = Expression.add (first, first); 3 Console.WriteLine (result);

Breakpoint Object Properties

Each property value is the first object and the result object, respectively.

    • Compiling an expression tree into a delegate

 LambdaExpression is one of the types derived from expression. Generic class expression<tdelegate> are also derived from lambdaexpression. The difference between expression and expression<tdelegate> is that a generic class identifies what kind of expression it is in the method of a static class, that is, it determines the return type and parameters. Obviously, this is represented by the tdelegate type parameter, which must be a delegate type. LambdaExpression has a compile method to create a delegate of the appropriate type. Expression<tdelegate> also has a method with the same name, but it statically types a delegate that returns the TDelegate type. Such as:

1 Expression first = expression.constant (5); 2 Expression result = Expression.add (first, first); 3 func<int> Add = expression.lambda<func<int>>(Result). Compile (); 4 // Ten
    • Convert a C#LAMBDA expression to an expression tree

Lambda expressions can be explicitly or implicitly converted to the appropriate delegate instances, but these are not the only transformations that can be made, but you can also require the compiler to build an expression tree from your lambda expression to create an instance of expression<tdelegate> at execution time. Such as

1 expression<func<int5; 2 func<int> add0 = re.compile (); 3 Console.WriteLine (add0 ());

The back of those content is really too complex, I really can not understand, and the daily use has not been used, there is no confidence to talk about this topic, want to go deep into the friends to understand, here to do it.

Please treatise.

16.c# the lambda expression and expression tree (ix-9.1-9.3)

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.