C # Lambda expressions

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

 
Delegate IntDel (IntI );
Del mydelegate = x => X * X;
IntJ = mydelegate (5);//J = 25

Create expression directory tree type:

 
UsingSystem. 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, such And Standard query operator parameters.

use the method-based syntax in method (as in the LINQ to objects and LINQ to XML), the parameter is of the delegate type . Using lambda expressions to create a delegate is the most convenient. For example, when you class (as in LINQ to SQL), the parameter type is , 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 the where call look 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.

In Or Lambda is not allowed on the left side of the operator.

All limitations applicable to anonymous methods also apply to lambda expressions.

Lambda expressions

The Lambda expression on the right is called a "Lambda expression ". Lambda expressions are being constructed Is 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 ()

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 ");

Lambda can reference "external variables" that are within the range of a 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 test = New Test ();
Test. testmethod ( 5 );

// Prove that del2 still has a copy
// Local variable J from testmethod.
Bool Result = test. del2 ( 10 );

// Output: True
Console. writeline (result );

Console. readkey ();
}
}

 

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.