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);
Del mydelegate = x => x * x;
int J = mydelegate(5); J =
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 class people
{
public int Age {get; set;} Setting properties
public string name {get; set;} Setting properties
Public people (int age,string name)//Set Property (constructor construct)
{
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 = new List<people >(); Creating generic objects
People P1 = new people ("guojing"); Create an Object
People P2 = new people ("wujunmin"); Create an Object
People P3 = new people ("muqing"); Create an Object
People P4 = new people (at "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 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 (Delegate (people p) {return p.age > 20;});
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 > 20);
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 => 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 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:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Namespace Lambdademo
{
Class Program
{
static void Main (string[] args)
{
Console.WriteLine ("Traditional Delegate code example:");
Findlistdelegate ();
Console.Write ("\ n");
Console.WriteLine ("Example of using anonymous methods:");
Findlistanonymousmethod ();
Console.Write ("\ n");
Console.WriteLine ("Example using lambda:");
Findlistlambdaexpression ();
}
Example of a traditional invocation delegate
static void Findlistdelegate ()
{
First, create a generic list class
List<string> list = new list<string >();
List. AddRange (new string[] {"ASP. NET course, "EE course", "PHP Course", "Data Structure Course"});
predicate<string> findpredicate = new predicate< string > (isbookcategory);
List<string> bookcategory = list. FindAll (findpredicate);
foreach (String str in bookcategory)
{
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 bool Isbookcategory (String str)
{
Return str. EndsWith ("course")? True:false;
}
Using anonymous methods for the search process
static void Findlistanonymousmethod ()
{
First, create a generic list class
List<string> list = new list<string >();
List. AddRange (new string[] {"ASP. NET course, "EE course", "PHP Course", "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 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);
}
}
Using lambda to implement the search process
static void Findlistlambdaexpression ()
{
First, create a generic list class
List<string> list = new list<string >();
List. AddRange (new string[] {"ASP. NET course, "EE 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 program's run results are shown in 2-7.
|
Figure 2-7 Running Results |
C # lambda expression