Lambda expression
A lambda expression is an anonymous function, an efficient expression similar to functional programming, and lambda simplifies the amount of code that needs to be written in development. It can contain expressions and statements, and can be used to create delegates or expression tree types, and supports inline expressions with input parameters that can be bound to delegates or expression trees. All lambda expressions use the lambda operator =>, and the operator reads "goes to". The left side of the lambda operator is the input parameter (if any), and the right is the expression or statement block. The lambda expression x + x * x is read as "x goes to X times X". You can assign this expression to a delegate type, as follows:
Delegate int del (int i); = x = x * x ; int j = mydelegate (5//
Lambda expression lambda expressions are evolved from. NET 2.0 and are the basis of LINQ, and mastering lambda expressions is a fast way to develop LINQ applications on the ground.
A lambda expression is, to some extent, another form of representation of an anonymous method. To facilitate the interpretation of lambda expressions, you first need to create a people class, as shown in the example code below.
Public classpeople { Public intAge {Get;Set; }//Setting Properties Public stringName {Get;Set; }//Setting Properties PublicPeople (intAgestringName//Setting properties (constructor construction) { This. Age = Age;//Initialize the property value of age This. name = name;//Initialize property value name } }
The code above defines a people class and includes a default constructor to initialize the age and name of the People object. In application design, there are many situations where you need to create collections of objects, and creating collections of objects facilitates search operations and sorting of objects to filter the appropriate objects in the collection. Using list for generic programming, you can create a collection of objects, as shown in the sample code below.
list<people> people =NewList<people> ();//Creating generic ObjectsPeople p1 =NewPeople ( +,"guojing");//Create an ObjectPeople p2 =NewPeople ( +,"Wujunmin");//Create an ObjectPeople p3 =NewPeople ( -,"muqing");//Create an ObjectPeople P4 =NewPeople ( at,"Lupan");//Create an ObjectPeople. Add (p1);//add an ObjectPeople. ADD (p2);//add an ObjectPeople. ADD (p3);//add an ObjectPeople. ADD (p4);//add an Object
The code above creates 4 objects, each of which initializes the age and first name and adds it to the list. When an application needs to filter objects in a list, for example to filter people older than 20, you need to filter from the list, as shown in the sample code below.
// Anonymous Methods ienumerable<people> results = people. Where (delegatereturn
The code above creates a result collection using the IEnumerable interface, and the collection is populated with people objects older than 20. Careful readers can find that an anonymous method is used here to filter because the method has no name and is filtered by using the age field of the people class object.
Although filtering is performed in the preceding code, using an anonymous method is often not easy to understand and read, whereas a lambda expression is easier to understand and read, and the sample code is as follows.
- IEnumerable<people> results = people. Where (people => People.age >);
The above code also returns a collection of people objects to the variable results, but its method of writing is easier to read, and from here you can see that the lambda expression is very similar in the format written to the anonymous method. In fact, when the compiler starts compiling and running, the lambda expression eventually behaves as an anonymous method.
Using an anonymous method does not create a method with no name, and the compiler creates a method that is not visible to the developer, which returns and populates the object that conforms to p.age>20 in the object of the People class to the collection. Similarly, with a lambda expression, when the compiler compiles, the lambda expression is also compiled into an anonymous method for the corresponding operation, but the lambda expression is easier to read than the anonymous method, and the lambda expression is formatted as follows.
- (parameter list) => expression or statement block
In the code above, the argument list is the People class, the expression or statement block is people.age>20, and using a lambda expression makes it easy to understand exactly how the statement is executed, although the anonymous method provides the same functionality and is not easily understood. By contrast, people = people.age > 20 is well understood as "returning a person older than 20." In fact, there is no advanced technique for lambda expressions, and lambda expressions can be seen as another form of representation of anonymous methods. After a lambda expression has been deserialized, it is no different from an anonymous method.
Comparing lambda expressions and anonymous methods, in an anonymous method, "(", ")" is a collection of the parameters of the method, which corresponds to the "(parameter list)" In the lambda expression, and the "{", "}" within the anonymous method is the statement block of the method, which corresponds to the "= =" in the lambda expression The expression or statement block item to the right of the symbol. Lambda expressions also contain some basic formats, which are as follows.
A lambda expression can have multiple arguments, a parameter, or no parameters. Its parameter types can be implicit or explicit. The sample code is as follows:
(x, y) = x * y//Multi-parameter, implicit type-=-expressionx = x *5 //single-parameter, implicit-type-=-expressionx = {returnX *5; }//single-parameter, implicit-type = statement block(intx) = x *5 //Single-parameter, explicit-type-=-expression(intX) = = {returnX *5; }//Single-parameter, explicit type = = Statement block() = Console.WriteLine ()//No Parameters
The above format is a valid form of a lambda expression, and when you write a lambda expression, you can omit the type of the parameter, because the compiler can infer the type of the parameter directly from the context, as shown in the example code below.
- (x, y) => x + y//multi-parameter, implicit type => Expression
The body of a lambda expression can be either an expression or a block of statements, which saves code writing.
"Example 2-5" traditional method, anonymous method and LAMDBA expression comparison.
(1) Create a console application Lamdbaprictice.
(2) Add 3 functions in the program, these 3 functions use the traditional delegate invocation, use anonymous method and Lamdba expression method to complete the same function, the contrast is different. The code is as follows:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespaceLambdademo {classProgram {Static voidMain (string[] args) {Console.WriteLine ("example of a traditional delegate code:"); Findlistdelegate (); Console.Write ("\ n"); Console.WriteLine ("examples of using anonymous methods:"); Findlistanonymousmethod (); Console.Write ("\ n"); Console.WriteLine ("examples of using lambda:"); Findlistlambdaexpression (); } //example of a traditional invocation delegate Static voidfindlistdelegate () {//first, create a generic list classlist<string> list =Newlist<string>(); List. AddRange (New string[] {"ASP. NET Courses","EE course","PHP Courses","Data Structure Course" }); predicate<string> findpredicate =Newpredicate<string>(isbookcategory); List<string> bookcategory =list. FindAll (findpredicate); foreach(stringStrinchbookcategory) {Console.WriteLine ("{0}\t", str); } } //predicate method, this method will be passed to the FindAll method to determine the classification of books and books Static BOOLIsbookcategory (stringstr) { returnStr. EndsWith ("Courses") ?true:false; } //using anonymous methods for the search process Static voidFindlistanonymousmethod () {//first, create a generic list classlist<string> list =Newlist<string>(); List. AddRange (New string[] {"ASP. NET Courses","EE course","PHP Courses","Data Structure Course" }); //here, the anonymous method is used to create a block of code directly for the delegate without having to create a separate methodlist<string> bookcategory =list. FindAll (Delegate(stringstr) { returnStr. EndsWith ("Courses") ?true:false; } ); foreach(stringStrinchbookcategory) {Console.WriteLine ("{0}\t", str); } } //using lambda to implement the search process Static voidfindlistlambdaexpression () {//first, create a generic list classlist<string> list =Newlist<string>(); List. AddRange (New string[] {"ASP. NET Courses","EE course","PHP Courses","Data Structure Course" }); //here, Lambda is used to create a delegate methodlist<string> bookcategory = list. FindAll ((stringstr) = str. EndsWith ("Courses")); foreach(stringStrinchbookcategory) {Console.WriteLine ("{0}\t", str); } } } }
The program's run results are shown in 2-7.
-
|
Figure 2-7 Running Results |
C # of Lambda expressions