"Lambda expressions" is an anonymous function and an efficient function-like programming expression. Lambda simplifiesCodeQuantity. It can contain expressions and statements and can be used to create a delegate or expression directory tree type. It supports inline expressions with input parameters that can be bound to the delegate or Expression Tree. All lambda expressions use the lambda operator =>, which is read as "goes ". The left side of the lambda operator is the input parameter (if any), and the right side is the expression or statement block. Lambda expressions x => X * x read as "X goes to X times X ". You can assign this expression to the delegate type as follows:
- Delegate int del (int I );
- DelMydelegate=X=>X * X;
- IntJ=Mydelegate(5 );//J=25
Lambda expressions lambda expressions are evolved from. NET 2.0 and are also the basis of LINQ. Familiar with Lambda expressions, you can quickly develop your own applications.
To some extent, lambda expressions are another manifestation of anonymous methods. To facilitate the interpretation of lambda expressions, you must first create a people class. The sample code is as follows.
-
- Public class people
-
- {
-
- Public int age {Get; set;} // sets attributes.
-
- Public string name {Get; set;} // you can specify attributes.
-
- Public people (INT age, string name) // sets attributes (constructor Construction)
-
- {
- This. Age= Age; // initialize the attribute value age
-
- This. Name= Name; // initialize the property name
-
- }
-
- }
The code above defines a people class and contains a default constructor that can initialize the age and name of the people object. In the ApplicationProgramIn design, in many cases, you need to create a set of objects. Creating a set of objects helps you search for and sort objects, so that you can filter objects in the set. Using list for generic programming, you can create a set of objects. The sample code is as follows.
- List<People>People=NewList<People>(); // Create a generic object
-
- PeopleP1=NewPeople (21, "guojing"); // create an object
-
- PeopleP2=NewPeople (21, "wujunmin"); // create an object
- PeopleP3=NewPeople (20, "muqing"); // create an object
-
- PeopleP4=NewPeople (23, "Lupan"); // create an object
-
- People. Add (P1); // Add an object
-
- People. Add (P2); // Add an object
- People. Add (P3); // Add an object
-
- People. Add (P4); // Add an object
The code above creates four objects, which initialize the age and name respectively and add them to the list. When the application needs to filter objects in the list, for example, to filter people older than 20 years old, you need to filter objects from the list. The sample code is as follows.
- // Anonymous method
- Ienumerable<People>Results=People. Where (delegate (People p) {return P. Age>20 ;});
The above Code creates a result set using the ienumerable interface, and the set is filled with people objects older than 20. Careful readers can find that an anonymous method is used for filtering, because the method has no name, and the age field of the People class object is used for filtering.
Although the above Code performs the filtering operation, the use of anonymous methods is often not easy to understand and read, while lambda expressions are easier to understand and read. The sample code is as follows.
- Ienumerable<People>Results=People. Where (People=>People. Age>20 );
The code above also returns a set of people objects to the variable results, but the method of writing it is easier to read. here we can see that Lambda expressions are very similar to anonymous methods in the format of writing them. In fact, when the compiler starts to compile and run, the lambda expression is eventually represented as an anonymous method.
The anonymous method is not used to create a method without a name. In fact, the compiler creates a method, which is invisible to developers, this method will match the object of the People class with P. age> 20 objects are returned and filled into the set. Similarly, when using lambda expressions, when the compiler compiles, lambda expressions are also compiled into an anonymous method for corresponding operations. However, lambda expressions are easier to read than anonymous methods, the format of lambda expressions is as follows.
- (Parameter list) =>Expression or statement Block
In the above Code, the parameter list is the people class, and the expression or statement block is the people. age> 20. Using lambda expressions makes it easy to understand how the statement is executed. Although anonymous methods provide the same functions, they are not easy to understand. In contrast, People => people. age> 20 can be well understood as "returning a person older than 20 ". Actually, lambda expressions have no advanced technology. Lambda expressions can be seen as another form of expression for anonymous methods. After lambda expressions are decompiled, they are no different from anonymous methods.
Compare lambda expressions and anonymous methods. In an anonymous method, "(", ")" is a set of parameters of the method, which corresponds to "(parameter list)" in the lambda expression) ", while" {","} "in the anonymous method is the statement block of the method, which corresponds to the expression or block item on the right of the" => "symbol in the lambda expression. Lambda expressions also contain some basic formats.
Lambda expressions can have multiple parameters, one parameter, or no parameters. The parameter type can be implicit or explicit. The sample code is as follows:
- (X, y) =>X * y // multiple parameters, implicit type =>Expression
-
- X=>X * 5 // single parameter, implicit type =>Expression
-
- X=>{Return x * 5;} // single parameter, implicit type =>Statement Block
-
- (Int x) =>X * 5 // single parameter, explicit type =>Expression
- (Int x) =>{Return x * 5;} // single parameter, explicit type =>Statement Block
-
- () =>Console. writeline () // No Parameters
The preceding format is a valid Lambda expression format. When writing a Lambda expression, you can ignore the parameter type because the compiler can deduce the parameter type based on the context. The sample code is as follows.
- (X, y) =>X + Y // multiple parameters, implicit type =>Expression
The body of a Lambda expression can be an expression or a statement block, which saves coding effort.
[Example 2-5] comparison between the traditional method, the anonymous method and the lamdba expression.
(1) Create the console application lamdbaprictice.
(2) Add three functions to the program. These functions use the traditional delegate call, anonymous method, and lamdba expression method to complete the same function. What are the differences between them. The Code is as follows:
-
- Using system;
- Using system. Collections. Generic;
-
- Using system. LINQ;
-
- Using system. text;
-
- Namespace lambdademo
-
- {
-
- Class Program
-
- {
-
- Static void main (string [] ARGs)
-
- {
-
- Console. writeline ("Traditional delegated code example :");
-
- Findlistdelegate ();
- Console. Write ("\ n ");
-
- Console. writeline ("example of using anonymous methods :");
-
- Findlistanonymousmethod ();
-
- Console. Write ("\ n ");
-
- Console. writeline ("example of using lambda :");
-
- Findlistlambdaexpression ();
-
-
- }
- // Example of a traditional call delegate
-
- Static void findlistdelegate ()
-
- {
-
- // Create a generic list class first
-
- List<String>List=NewList<String>();
- List. addrange (New String [] {"ASP. NET course", "J2EE course", "php course", "Data Structure Course "});
-
- Predicate<String>Findpredicate=NewPredicate<String>(Isbookcategory );
-
- List<String>Bookcategory=List. Findall (findpredicate );
- Foreach (string STR in bookcategory)
-
- {
-
- Console. writeline ("{0} \ t", STR );
-
- }
-
- }
-
- // The predicate method. This method is passed to the findall Method for Determining the category of books and books.
-
- Static bool isbookcategory (string Str)
-
- {
- Return Str. endswith ("Course ")? True: false;
-
- }
-
- // Use the anonymous method for the search process
-
- Static void findlistanonymousmethod ()
-
- {
-
- // Create a generic list class first
- List<String>List=NewList<String>();
-
- List. addrange (New String [] {"ASP. NET course", "J2EE course", "php course", "Data Structure Course "});
-
- // Here, create a code block for the delegate directly using the anonymous method, instead of creating a separate Method
- List<String>Bookcategory=List. Findall
-
- (Delegate (string Str)
-
- {
-
- Return Str. endswith ("Course ")? True: false;
-
- }
- );
-
- Foreach (string STR in bookcategory)
-
- {
-
- Console. writeline ("{0} \ t", STR );
-
- }
-
- }
-
- // Use Lambda to implement the search process
- Static void findlistlambdaexpression ()
-
- {
-
- // Create a generic list class first
-
- List<String>List=NewList<String>();
-
- List. addrange (New String [] {"ASP. NET course", "J2EE course", "php course", "Data Structure Course "});
- // Here, lambda is used to create a delegate Method
-
- List<String>Bookcategory=List. Findall (string Str) =>Str. endswith ("Course "));
-
- Foreach (string STR in bookcategory)
-
- {
-
- Console. writeline ("{0} \ t", STR );
- }
-
- }
-
-
- }
-
- }
The running result of the program is 2-7.
|
Figure 2-7 running results |