[. Net Object-Oriented programming advanced] (5) Lamda expressions (1) Create delegation and lamda expressions

Source: Internet
Author: User

[. Net Object-Oriented programming advanced] (5) Lamda expressions (1) Create delegation and lamda expressions

[. Net Object-Oriented programming advanced] (5) Lamda expressions (1) Create Delegation 

This section introduces: 

By learning Lambda expressions, you can learn how to create a delegate and expression directory tree, learn more about Lambda features, and make your code clearer, concise, and efficient.

Before reading: 

Before learning this section, you must have the following knowledge:

A. Generic (see [. net idea Object-Oriented Programming Basics] generic programming (18) generic)

B. Linq BASICS (refer to [. net idea Object-Oriented Programming Basics] idea (19) LINQ basics)

C. Use of Linq (refer to [. net idea Object-Oriented Programming Basics] (20) Use of LINQ)

D. Delegate (refer to [. net pipeline Object-Oriented Programming Basics] pipeline (21) pipeline delegation)

E. Events (see [. net idea Object-Oriented Programming Basics] (22) events)

Through the introduction in the. net Object-Oriented Programming basics series, we have initially used Lambda expressions for Linq queries. In this section, we will learn more about Lambda expressions.

1. About Lambda 

Lambda expressions are anonymous functions that can be used to create a delegate or expression directory tree.

The above is Microsoft's definition of Lambda expressions. From this definition, we can see that the existence of Lambda mainly involves two things:

A. Create A Delegate) 

B. Create an Expression Tree) 

In addition, Lambda expressions are essentially anonymous methods (or anonymous functions ).

We will start with these two methods to learn more about the convenience that Lambda brings to us.

2. Lambda expressions 

Lambda expressions are composed of the following:

Zero parameter: () => expr

One parameter: (param) => expr or param => expr

Multiple parameters: (param-list) => expr

All Lambda expressions use the Lambda operator =>, which reads as "goes"

When there is only one parameter, the parentheses on the right can be omitted.

The following is an example of writing:

// Zero parameter () => MethodName () // one parameter (x) => x + xX => x + x // two or more parameters (m, n) => m. length> n // explicit type parameter (int x, string y) => y. length> x

In the preceding example, the explicit type parameter can be explicitly defined when the compiler cannot infer its parameter type.

3. Lambda statements

Lambda statements are similar to Lambda expressions, but the right part is written in {}.

Lambda statements are composed of the following:

(Input parameters) =>{ statement ;}

Example:

delegate void TestDelegate(string s);…TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };myDel("Hello");

4. asynchronous Lambda (async and await)

By studying in. net Object-Oriented Programming basics, we learned that events are also a special type of delegation. Lambda can be used to create delegates, that is, they can also create events.

The following is an example:

First, let's take a look at the implementation of a normal button click event and Lambda statement writing.

The following is a general statement:

This. myButton. click + = new System. eventHandler (this. myButton_Click); // The event is usually delegated in private void myButton_Click (object sender, EventArgs e) {MessageBox. show ("Hello, I am a button click event! ");}

Lambda is written as follows:

// Write the event Lambda statement myButton. Click + = (sender, e) =>{ MessageBox. Show ("Hello, I am a button to Click the event! This is the Lambda statement ");};

There are many examples in the previous sections of the above two statements.

Next let's take a look at asynchronous events:

// The normal Syntax of asynchronous events is private async void asyncButton_Click (object sender, EventArgs e) {await MyMethodAsync (); MessageBox. Show ("Hello, I am clicking the event button! Asynchronous! ");} Async Task MyMethodAsync () {await Task. Delay (1000 );}

We use Lambda to rewrite the above asynchronous events:

// AsyncButton. Click + = async (sender, e) =>{ await MyMethodAsync (); MessageBox. Show ("Hello, I am clicking the event button! Asynchronous! This is the Lambda statement ") ;}; async Task MyMethodAsync () {await Task. Delay (1000 );}

The above asynchronous event is represented by async in the event Delegate phase. In the event processing phase, await keywords are used to specify an Asynchronous Method.

Lambda statements are also concise and effective for asynchronous events.

5. Lambda expressions for standard query operations

5.1 wildcard delegated use of Lambda

We mentioned three common generic delegation types in the [. net pipeline Object-Oriented Programming Basics] pipeline (21) pipeline delegation section.

Action (no returned value generic delegation)

Func (with returned value generic delegation)

Predicate (the return value is a bool type generic delegate)

This section does not repeatedly describe generic delegation. If you are not familiar with generic delegation, refer to. We will only illustrate generic delegation and its Lambda writing.

// Action generic delegation without return value type // anonymous method declaration and call Action <int, int> act = delegate (int a, int B) {Console. writeLine (a + "+" + B + "=" + (a + B) ;}; act (11, 22); // expression declaration and call Action <int, int> actlamloud = (a, B) => {Console. writeLine (a + "+" + B + "=" + (a + B) ;}; actlameline (111,222 ); // Func generic delegation with returned values // anonymous method declaration and call Func <int, int, string> acc = delegate (int a, int B) {return (a + "+" + B + "=" + (a + B) ;}; Console. writeLine (acc (11, 22); // expression declaration and call Func <int, int, string> ac = (a, B) ==>{ return (a + "+" + B + "=" + (a + B) ;}; Console. writeLine (ACS (111,222 ));

5.2 use Lambda in Linq

For the use of Lambda expressions in Linq [. net idea Object-Oriented Programming Basics] (20) the usage of LINQ is described in detail. For unfamiliar users, refer to. Below we illustrate several common Lambda query methods.

5.2.1 Count

// Query the odd-Lambda statements in the following number: int [] numbers = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int oddNumbers = numbers. count (n => n % 2 = 1); Console. writeLine ("odd number:" + oddNumbers. toString () + ", Lambda writing "); // query the odd number of columns in the following code: var oddNumbersFunc = (from num in numbers where num % 2 = 1 select num ). count (); Console. writeLine ("odd number:" + oddNumbersFunc. toString () + "pieces, written in the Linq query ");

The running result is as follows:

5.2.2 when TakeWhile meets the conditions, a set is returned.

// If TakeWhile satisfies the specified conditions, the system returns the result. If 6 is detected in number, 8 and 9 do not meet the conditions, returns 5 4 1 3 int [] numbers = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}; var firstNumbersLessThan6 = numbers. takeWhile (n => n <6); Console. writeLine ("the number of returned results if the condition is met:" + firstNumbersLessThan6.Count (). toString () + ", Lambda writing"); // The second index parameter indicates the index position of n, string NewNumber = String. empty; numbers. takeWhile (n, index) => n> = index ). toList (). forEach (m => NewNumber + = m + ""); Console. writeLine ("the number returned when the condition is met:" + NewNumber + ", Lambda writing ");

The running result is as follows:

6. Lambda type inference

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

// Lambda type inference List <MyClass> list = new List <MyClass> () {new MyClass () {at1 = "aaa", at2 = 2, at3 = DateTime. now}, new MyClass {at1 = "bbb", at2 = 5, at3 = DateTime. parse ("2015-06-07")}, new MyClass {at1 = "aaa", at2 = 1, at3 = DateTime. parse ("2010-11-12") }}; Console. writeLine ("the elements whose at1 is aaa include:" + list. where (m => m. at1 = "aaa "). count () + "Count, Lambda writing ");
class MyClass {    public  string at1 { get; set; }    public int at2 { get; set; }    public DateTime at3 { get; set; }}

The running result is as follows:

The general rules of Lambda are as follows:

A. the number of parameters contained in Lambda must be the same as that contained in the delegate type.

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

C. 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 conventional type system does not have the internal concept of "Lambda expression. However, it is convenient to talk about the "type" of lambda expressions in an informal way. In these cases, the type refers to the Expression type converted to the delegate type or lambda Expression.

7. variable range of Lambda expressions

In [. net hotspot Object-Oriented Programming Basics] when talking about anonymous methods, the anonymous method can reference external variables in the Manyuan, which are also mentioned in the previous example.

Here is an example:

Class Program {static int num = 2; static void Main (string [] args) {int num2 = 7; // The variable range of the Lambda expression // relative to the following expression, the following test calls int [] numbers2 = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}; // sum of the numbers greater than num and less than num2. int sum = numbers2.Where (m => m> num & m <num2 ). sum (); Console. writeLine ("sum greater than num and less than num2:" + sum); Console. readKey ();}}

The following rules apply to variable ranges in lambda expressions:

A. the captured variables will not be recycled as garbage until the delegate that references the variables meets the garbage collection conditions.

B. variables introduced in lambda expressions cannot be seen in external methods.

C. Lambda expressions cannot directly capture the ref or out parameters from the closed method.

D. The return statement in the Lambda expression does not cause the closed method to return.

E. If the target of the jump statement is outside the block, the lambda expression cannot contain the goto statement, break statement, or continue statement inside the lambda function. Similarly, if the target is inside the block, it is also incorrect to use the jump statement outside the lambda function block.

8. Key points:

This section mainly describes:

The Application of Lambda expressions in the creation of delegation;

The Application of Lambda expressions in Linq queries;

Application of Lambda statements in asynchronous events;

Lambda has two features: type inference and external variable reference.

In the next section, another feature of Lambda is to create an Expression Tree ).

========================================================== ========================================================== ====================

 Returned directory

<If it is helpful to you, please click here for recommendations. If yes

Do not understand or make a mistakePoints, Please exchange more>

<If you have any difficulty reading this series of articles, please read. net Object-Oriented Programming basics first>

<Reprinted statement: technology requires a spirit of sharing. You are welcome to repost the article in this blog, but please note the copyright and URL>

. NET exchange group: 467189533

========================================================== ========================================================== ====================

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.