-------------------------------------------
1. What is a Lambda expression?
A Lambda expression is an anonymous function that can contain expressions and statements and can be used to create a delegate or expression directory tree. All lambda expressions use the lambda Operator=>The operator reads "goes ". The left side of the lambda operator is the input parameter (if any), and the right side contains the expression or statement block.
Lambda expression: x => X * x
To understand lambda, we need to first look at anonymous functions. What are anonymous functions? An anonymous function is an "inline" statement or expression that can be used wherever the delegate type is required. There are two types of anonymous functions: lambda expressions (C #3.0) and anonymous methods (C #2.0). This "inline" does not seem to be well understood, therefore, the generation and use of anonymous functions are described in detail starting from the use history of delegation:
(Delegate is a type of packaging method call. Just like the type, you can pass the delegate instance between methods and call the delegate instance just like the method .)
C #1.0: Before 2.0, the only way to declare a delegate is to use the naming method, that isCodeExplicitly initialize the delegate to create the delegated instance. For example:
// Declare a delegate Delegate Void Testdelegate ( String S ); Class Testclass { Static Void Main (){ // Original delegate syntax required // Initialization with a named method. Testdelegate testdela = New Testdelegate (testclass. dowork ); // Invoke the delegates. Testdela ( " Hello. " );} // The method associated with the named delegate: Static Void Dowork ( String K) {system. Console. writeline (k );}}
C #2.0: In 2.0, the concept of anonymous method was introduced as a way to write untitled inline statement blocks that can be executed in a delegate call, that is to say, you do not need to create a separate method in advance, so the coding system overhead required for instantiating the delegate is reduced. For example:
// Declare a delegate Delegate Void Testdelegate ( String S ); Class Testclass { Static Void Main (){ // C #2.0: A delegate can be initialized // Inline code, called an "anonymous method." This // Method takes a string as an input parameter. Testdelegate testdelb = Delegate ( String S) {console. writeline (s );}; // Invoke the delegates. Testdelb ( " Hello 2 " );}}
C #3.0: introduces lambda expressions, which are similar to anonymous methods but more expressive and concise. Lambda expressions gradually replace anonymous methods as the preferred method for writing Inline code. For example:
// Declare a delegate Delegate Void Testdelegate ( String S ); Class Testclass { Static Void Main (){ // C #3.0. A delegate can be initialized // A Lambda expression. The Lambda also takes a string // As an input parameter (X). The type of X is inferred by the compiler. Testdelegate testdelc = (x) => {Console. writeline (x );}; // Invoke the delegates. Testdelc ( " Hello 3. " );}}
2. Lambda expression format:
(Parameter list) => expression or statement block. The parameter list on the Left can have multiple parameters, one parameter, or no parameter. The parameter type can be implicit or explicit. For example:
(X, y) => X * y // Multiple parameters, implicit type => Expression X => X * 10 // Single parameter, implicit type => Expression X => { Return X * 10 ;} // Single parameter, implicit type => statement Block ( Int X) => X * 10 // Single parameter, explicit type => Expression (Int X) => { Return X * 10 ;} // Single parameter, explicit type => statement Block () => Console. writeline () // No Parameter
From the above statements, we can draw some key points of the lambda expression:
A. the parameter type can be ignored because it can be inferred based on the context;
// declare a DeleGate DeleGate void testdelegate ( string S); class testclass { static void main () { /// from the parameter defined by the delegate, X is of the string type. testdelegate testdelc = (x) => {console. writeline (x) ;}}}
B. The subject of the expression can be the expression (x, y) => X * Y) or the statement block (x => {return x * 10 ;})
C. The arguments passed in by lambda expressions will be involved in type inference and method overload analysis.
D. Lambda expression expressions and expression bodies can be converted into expression trees.
3. Lambda expressions and delegate types
// Declare a delegate Public Delegate Int Testintdelegate ( Int G ); Class Testclass { Static Void Main (){ // Pass lambda expressions Test (y => y * Y );} Public Void Test (testintdelegate Ti ){ Int Area = Ti ( 10 );}}
The test parameter of the method is to delegate the testintdelegate type, and we directly input the lambda expression test (y => y * Y) during the call. Therefore, the lambda expression can be converted to the delegate type, however, the following requirements must be met:
A. the number of parameters is the same.
B. The parameter types are the same. Note that implicit types must be involved in type discrimination.
C. The return type of the delegate must be the same as that of Lambda, whether it is an expression or a statement block.
4. Lambda expressions and Expression Tree
The typical Declaration Form of the Expression Tree is
1: func <int, int> func = input => input * input;
2: expression <func <int, int> Expression = input => input * input;
Here we needSystem. LINQ. ExpressionsIn the namespace, expression <t>, and T is the type of the delegate that defines the expression signature. Let's look at the complete code used in the Expression Tree:
1: static void main (string [] ARGs)
2 :{
3: func <int, int> func = input => input * input;
4: console. writeline (func (3). tostring ());
5:
6: expression <func <int, int> Expression = input => input * input;
7: func <int, int> fun = expression. Compile ();
8: console. writeline (fun (5). tostring ());
9:
10: console. Readline ();
11 :}
The Expression Tree is used to describe the expression. An advanced tree is provided to represent an expression. Therefore, you can simply understand the purpose of a user expression;
Use Expression Tree:
A. expressions can be converted into delegates and called.
B. Convert the expressions to SQL so that they can be executed by the server (this is done by LINQ to SQL)
C. Convert the expressions to XML and write them to the disk. Convert an expression to a custom format. You can use the network protocol to relax the expression to the server, create a new expression tree, and then execute and/or (and/or) according to it ).
By using Lambda's support for the Expression Tree and the iqueryable <t> interface, a framework developer who builds a data provider can ensure that developers write clean code, it runs fast and efficient on any data source (such as databases, XML files, in-memory objects, Web Services, and LDAP systems.
5. Summary
Generally, the anonymous method replaces the lambda expression, and only uses the lambda expression when the statements have less functions. Otherwise, the written code may be less readable, this will cause unnecessary trouble for future maintenance and modification. Lambda is widely used in LINQ. As the learning progresses, lambda expressions and expression trees are constantly supplemented and corrected.
Reprinted from: http://blog.csdn.net/zhaozhongju/article/details/3137428
--------------------------------------------------------------------
Summary:
The syntax of lambda expressions is as follows:
(Param1, param2..., paramn) =>{ expression 1; expression 2; return value ;}
Param1. .. in the above syntax... paramn indicates the parameter of the method (no need to determine the type, C # compiler will do this for us) and {...} the content is exactly the same as the content in the method body. Essentially, the lamdba expression is still in the delegate format after being compiled by the C # compiler. That is to say, the lamdba expression is only improved at the syntax level, it is not a new command provided by IL.
// If delegate does not have a parameter, you can only write (), as shown in the following method: Public Delegate Void Method1 (); Public Void Test () {Method1 Method1 = () => { Int I = 4 ; I + = 6 ;};} // If delegate has only one parameter, the brackets on both sides of the parameter can be left empty. Public Delegate Void Method2 ( Int I ); Public Void Test () {method2 method2 = I => {I ++; I + = 6 ;};} // If delegate has a return value, the last statement in {...} needs to use return to return the corresponding value. Public Delegate Int Method3 ( Int X, Int Y ); Public Void Test () {method3 method3 = (X, y) => {x ++; y ++;Return X + Y ;};}