C#LAMDBA Expressions and Delegates

Source: Internet
Author: User

Introduced:

the Lambda expression " (lambda expression) is an anonymous function, in the C # 3.0 introduced in the Lambda expression, which is a simplification of anonymous functions, can contain expressions and statements, and can be used to create delegates or expression tree types.

How to create


format: (formal parameter list) = = {function Body}

to createLambdaexpression that needs to beLambdaoperator=on the left, specify the input parameters (if any), and then enter an expression or statement block on the other side. For example,LambdaAn expressionx = x * xrefers to the namingxthe parameters and returnsxthe value of the square. as the following example shows, you can assign this expression to a delegate type:

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

Note : The function body can be enclosed in curly braces for more than one statement.

The above function body can also be written as

Del MyDelegate = x = = {return x * x;};


Use Lambda An expression

the = = operator has an assignment operator (=) Same priority and right-associative operation

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

(x, y) = x = = Y

Use LAMDBA Statement


Statement Lambda is similar to an expression lambda expression, except that the statement is enclosed in curly braces:

Delegatevoid testdelegate (string s); Testdelegatemydel = n = {string s = n + "" + "world"; Console.WriteLine (s); }; Mydel ("Hello");

How the code uses LAMDBA

Lambda is used as a parameter to a standard query operator method (such as where) in a method-based LINQ query . The parameter is the delegate type system.func<t, tresult>. It is most convenient to create this delegate using a LAMBDA expression .  

See Example

Public delegate TResult func<targ0, tresult> (TArg0 arg0)
 

you can instantiate a delegate as func<int,bool> MyFunc, where int is the input parameter and bool is the return value. The return value is always specified in the last type parameter. Func<int, String, bool> definition contains two input parameters (int and string) and returns a delegate of type bool. When the following Func delegate is called, the delegate returns TRUE or false to indicate whether the input parameter equals 5:

func<int,bool> MyFunc = x = x = = = 5;boolresult = MyFunc (4); Returns false of course

A small example used in the project public commoditycollection Load (string type)        {             return this. Load (p = =            {                p.appenditem ("Code", type);            });        }


the load in return method is actually a delegate with a generic type , and P is implemented for inheritance methods of Sqlclausebuilderuw

[Serializable]public abstract class sqlclausebuilderuw:sqlclausebuilderiuw{protected Sqlclausebuilderuw ();p ublic Sqlclausebuilderuw appenditem<t> (String DataField, T data, String op, String template);p ublic Sqlclausebuilderuw Appenditem<t> (String DataField, T data, String op, String template, bool isexpression);p rotected override Sqlclause Builderitembase Createbuilderitem ();}

Public tcollection Load (action<wheresqlclausebuilder> whereaction);
 

namespacesystem{//Abstract://     encapsulates a method that has only one parameter and does not return a value. Parameters://   obj://The     parameters of the method encapsulated by this delegate. Type parameter://   t://The     parameter type of the method encapsulated by this delegate. public delegate void Action<in t> (T obj);


Summary:


comprehensive application can be seen LAMDBA The method of querying can be simplified, and the Linq the use of multiple and generic delegates, enumeration of the where method is used together. Is that the query method simplifies a lot, but the internal structure is the same as the anonymous function. is also just contact understanding, deficiencies also please understand.



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.