Featured by msdn: lambda expressions (C # programming guide)

Source: Internet
Author: User

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 =>, which 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 expressionsX => X * xRead as "X goes to X times X ". You can assign this expression to the delegate type as follows:

 
Delegate int del (int I); del mydelegate = x => X * X; Int J = mydelegate (5); // J = 25

Create expression directory tree type:

 
Using system. LINQ. Expressions; //... expression <del> = x => X * X;

=>The operator has (=) Has the same priority and is the right combination operator.

Lambda is used in method-based LINQ queries, suchWhereAndWhereStandard query operator parameters.

Use the method-based syntax in Enumerable Class Where The parameter is the delegate type when the method is used (like in LINQ to objects and LINQ to XML ).System..::.Func<(<(T, tresult>)>) . Using lambda expressions to create a delegate is the most convenient. For example, when you System. LINQ..::.Queryable When the same method is called in the class (as in LINQ to SQL), the parameter type is System. LINQ. Expressions..::.Expression <Func>, in which func is any func delegate that contains up to five input parameters. Similarly, lambda expressions are just a very concise way to construct the expression directory tree. Although the types of objects created through Lambda are actually different, Lambda makes Where The call looks similar.

In the previous example, note that the delegate signature hasIntType of implicit type input parameter, and returnInt. You can convert a Lambda expression to a delegate of this type because the expression also has an input parameter (X), And a compiler can be implicitly convertedIntType. (Type inference will be discussed in detail in the following sections .) When you call a delegate using input parameter 5, it returns Result 25.

Lambda is not allowed on the left side of the IS or as operator.

All limitations applicable to anonymous methods also apply to lambda expressions. For more information, seeAnonymous method (C # programming guide).

Lambda expressions

The Lambda expression on the right is called a "Lambda expression ". Lambda expressions are being constructedExpression directory treeIs widely used. Lambda expressions return the results of expressions in the following basic form:

(Input parameters) => Expression

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

 
(X, y) => X = y

Sometimes, the compiler is difficult or unable to deduce 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 ()

In the previous example, note that the body of a Lambda expression can contain method calls. However, if you want to create an expression directory tree that will be used in another domain (such as SQL Server), you should not use method calls in lambda expressions. The context outside the method runtime in the. NET public language will be meaningless.

Lambda statements

Lambda statements are similar to lambda expressions, but they are enclosed in braces:

 
(Input parameters) =>{ statement ;}

The body of a Lambda statement can contain any number of statements. However, there are usually no more than two or three statements.

 
Delegate void testdelegate (string S );... Testdelegate MYDEL = n => {string S = N + "" + "world"; console. writeline (s) ;}; MYDEL ("hello ");

Like an anonymous method, Lambda statements cannot be used to create expression directory trees.

Lambda with standard query Operators

Many standard query operators have input parameters, whose types are generic delegated.Func<(<(T, tresult>)>)One of the series.Func<(<(T, tresult>)>)The delegate uses the type parameter to define the quantity and type of input parameters and the return type of the delegate.FuncDelegation is useful for encapsulating User-Defined expressions that are applied to each element in a set of source data. For example, assume that the following types of delegation exist:

 
Public Delegate tresult func <targ0, tresult> (targ0 arg0)

The delegate can be instantiatedFunc <int, bool> myfunc, WhereIntIs input parameter,BoolIs the return value. The return value is always specified in the last type parameter.Func <int, String, bool>The definition contains two input parameters (IntAndString) And the return type isBool. InFuncDuring delegation, the delegate returns true or false to indicate whether the input parameter is equal to 5:

 
Func <int, bool> myfunc = x => X = 5; bool result = myfunc (4); // returns false of course

When the parameter type isExpression <func>You can also provide lambda expressions, such as the standard query operators defined in system. LINQ. queryable. If you specifyExpression <func>Parameter, Lambda will compile as the expression directory tree.

A standard query operator is displayed here,CountMethod:

 
Int [] numbers = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}; int oddnumbers = numbers. count (n => N % 2 = 1 );

The compiler can infer the type of the input parameter, or you can explicitly specify this type. This special Lambda expression calculates the integer (NThe number of integers divided by 2, and the remainder is 1.

The following method generates a sequence containing all elements that appear before "9" in the number array, because "9" is the first number in the sequence that does not meet the conditions:

VaR firstnumberslessthan6 = numbers. takewhile (n => n <6 );

This example shows how to specify multiple input parameters by including the input parameters in parentheses. This method returns all elements in the number array until a number with a value smaller than its position is encountered. Do not set the lambda operator (=>) And operators greater than or equal (=>.

 
VaR firstsmallnumbers = numbers. takewhile (n, index) => N> = index );
Type inference in Lambda

When writing lambda, you usually do not need to specify a type for the input parameter, because the compiler can infer the type based on the lambda subject, basic delegate type, and other factors described in the C #3.0 language specification. For most standard query operators, the first input is the type of elements in the source sequence. Therefore, if you want to queryIenumerable <customer>, The input variable is inferredCustomerObject, which means you can access its method and attributes:

 
Customers. Where (C => C. City = "London ");

The general rules of Lambda are as follows:

    • Lambda must contain the same number of parameters as the delegate type.

    • Each input parameter in Lambda must be implicitly converted to its corresponding delegate parameter.

    • The return value (if any) of Lambda must be implicitly converted to the return type of the delegate.

Note that the lambda expression itself does not have a type, because the general type system does not have the internal concept of "Lambda expression. However, sometimes the lambda expression type is not formally discussed ". In these cases, the type refers to the conversion of the delegate type or Lambda expressionExpressionType.

Variable range in lambda expressions

Lambda can reference "external variables" that are within the scope of the closed method or type in which Lambda is defined. Variables captured in this way will be stored for use in lambda expressions, even if the variables are otherwise out of range or recycled as garbage. An external variable must be explicitly allocated before it can be used in a Lambda expression. The following example demonstrates these rules:

Delegate bool D (); Delegate bool D2 (int I); Class test {d del; d2 del2; Public void testmethod (INT input) {Int J = 0; // initialize the delegates with Lambda expressions. // note access to 2 outer variables. // del will be invoked within this method. del = () => {J = 10; return j> input ;}; // del2 will be invoked after testmethod goes out of scope. del2 = (x) => {return x = J ;}; // demonstrate value of J: // output: J = 0 // The delegate has not been invoked yet. console. writeline ("J = {0}", J); // invoke the delegate. bool boolresult = del (); // output: J = 10 B = true console. writeline ("J = {0 }. B = {1} ", J, boolresult);} static void main () {test = new test (); test. testmethod (5); // prove that del2 still has a copy of // local variable J from testmethod. bool result = test. del2 (10); // output: True console. writeline (result); console. readkey ();}}

The following rules apply to variable ranges in lambda expressions:

    • The captured variables will not be recycled as garbage until the delegation of the referenced variables exceeds the permitted range.

    • Variables introduced in lambda expressions cannot be seen in external methods.

    • Lambda expressions cannot be directly captured from the closed MethodRefOrOutParameters.

    • The Return Statement in the lambda expression does not cause the return of the closed method.

    • Lambda expressions cannot containGotoStatement,BreakStatement orContinueStatement.

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.