. C #-Lambda expression

Source: Internet
Author: User

Lambda expression

Theory:

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 = 25

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)        //Setting properties (constructor construction)         {               this.age = age;                  //Initialize the property value age            this.name = name;                //Initialize the property value name          }     }

The preceding code defines a people class and includes a default constructor that initializes 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 (21,  "Wujunmin");      //Create an Object    people p3 = new people (20,  "muqing");        //Create an Object    people p4 = new people (23,   "Lupan");         //creates an object    people. Add (p1);                      //adds an object    people. ADD (p2);                      //adds an object    people. ADD (p3);                     //adding an object     people. ADD (p4);                      //adding 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.

    1. Anonymous methods

    2. 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 parameter

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.


Instance:

"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 ("Delegate example:");             findlistdelegate ();             console.writeline ("Anonymous example:");             findlistanonymousmethod ();             console.writeline ("Lambda example:");             findlistlambdaexpression ();             console.readline ();}         //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 class",  "J2ee class",  "Data  Instructure class ", " php  "&NBSP;});             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&NBSP;STR) {             return str. EndsWith ("class")  ? true : false;}         static void findlistanonymousmethod () {             //first create a generic list class               list <string> list = new list <string> ();             list. AddRange (new string[] { "Asp.net class",  "J2ee class",  "Data instructure class",  "PHP class"  });             //here, use the anonymous method to create a block of code directly for the delegate. Instead of having to create a separate method               list<string > bookcategory = list. findall                 ( Delegate (STRING&NBSP;STR) {                     return str. EndsWith ("class")  ? true : false;});             foreach  (string str in  bookcategory) {                 console.writeline ("{0}\t", str);}}         //using LAMBDA to implement the search process          static void findlistlambdaexpression () {            //first creates a generic list class                list <string> list =  new List<string> ();             List. AddRange (new string[] {  "Asp.net class",  "J2ee class",  "Data  Instructure class ", " Php class "&NBSP;});             //here, Lambda is used to create a delegate method                list<string> bookcategory = list. FindAll ((STRING&NBSP;STR) =>str. EndsWith ("class"));            foreach  ( String str in bookcaTegory) {                 Console.WriteLine ("{0}\t", str);}}}

Results:


650) this.width=650; "title=" Capture.png "src=" http://s3.51cto.com/wyfs02/M01/6D/A0/ Wkiol1vog1gja3tbaacu9i5cotu231.jpg "alt=" Wkiol1vog1gja3tbaacu9i5cotu231.jpg "/>

Reference:
Http://www.cnblogs.com/kingmoon/archive/2011/05/03/2035696.html

This article comes from the "Ricky's blog" blog, please be sure to keep this source http://57388.blog.51cto.com/47388/1656376

. C #-Lambda expression

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.