C # Lambda expressions

Source: Internet
Author: User

Lambda expressions

"Lambda expression" is an anonymous function and an efficient function-like programming expression. Lambda simplifies the amount of code to be written during development. 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:

  1. Delegate int del (int I );
  2. Del mydelegate = x => X * X;
  3. Int J = 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.

  1. Public class people
  2. {
  3. Public int age {Get; set;} // sets attributes.
  4. Public string name {Get; set;} // you can specify attributes.
  5. Public people (INT age, string name) // sets attributes (constructor Construction)
  6. {
  7. This. Age = age; // initialize the attribute value age
  8. This. Name = Name; // initialize the attribute name.
  9. }
  10. }

The code above defines a people class and contains a default constructor that can initialize the age and name of the people object. In application design, you need to create a set of objects in many cases. Creating a set of objects facilitates searching and sorting 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.

  1. List <people> People = new list <people> (); // create a generic object
  2. People p1 = new people (21, "guojing"); // create an object
  3. People P2 = new people (21, "wujunmin"); // create an object
  4. People P3 = new people (20, "muqing"); // create an object
  5. People P4 = new people (23, "Lupan"); // create an object
  6. People. Add (P1); // Add an object
  7. People. Add (P2); // Add an object
  8. People. Add (P3); // Add an object
  9. 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.

  1. // Anonymous method
  2. 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.

  1. 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.

  1. (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:

  1. (X, y) => X * y // multiple parameters, implicit type => Expression
  2. X => X * 5 // single parameter, implicit type => Expression
  3. X =>{ return x * 5;} // single parameter, implicit type => statement Block
  4. (Int x) => X * 5 // single parameter, explicit type => Expression
  5. (Int x) =>{ return x * 5;} // single parameter, explicit type => statement Block
  6. () => 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.

  1. (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:

  1. Using system;
  2. Using system. Collections. Generic;
  3. Using system. LINQ;
  4. Using system. text;
  5. Namespace lambdademo
  6. {
  7. Class Program
  8. {
  9. Static void main (string [] ARGs)
  10. {
  11. Console. writeline ("Traditional delegated code example :");
  12. Findlistdelegate ();
  13. Console. Write ("\ n ");
  14. Console. writeline ("example of using anonymous methods :");
  15. Findlistanonymousmethod ();
  16. Console. Write ("\ n ");
  17. Console. writeline ("example of using lambda :");
  18. Findlistlambdaexpression ();
  19.  
  20. }
  21. // Example of a traditional call delegate
  22. Static void findlistdelegate ()
  23. {
  24. // Create a generic list class first
  25. List <string> List = new list <string> ();
  26. List. addrange (New String [] {"ASP. NET course", "J2EE course", "php course", "Data Structure Course "});
  27. Predicate <string> findpredicate = new predicate <string> (isbookcategory );
  28. List <string> bookcategory = List. findall (findpredicate );
  29. Foreach (string STR in bookcategory)
  30. {
  31. Console. writeline ("{0} \ t", STR );
  32. }
  33. }
  34. // The predicate method. This method is passed to the findall Method for Determining the category of books and books.
  35. Static bool isbookcategory (string Str)
  36. {
  37. Return Str. endswith ("Course ")? True: false;
  38. }
  39. // Use the anonymous method for the search process
  40. Static void findlistanonymousmethod ()
  41. {
  42. // Create a generic list class first
  43. List <string> List = new list <string> ();
  44. List. addrange (New String [] {"ASP. NET course", "J2EE course", "php course", "Data Structure Course "});
  45. // Here, create a code block for the delegate directly using the anonymous method, instead of creating a separate Method
  46. List <string> bookcategory = List. findall
  47. (Delegate (string Str)
  48. {
  49. Return Str. endswith ("Course ")? True: false;
  50. }
  51. );
  52. Foreach (string STR in bookcategory)
  53. {
  54. Console. writeline ("{0} \ t", STR );
  55. }
  56. }
  57. // Use Lambda to implement the search process
  58. Static void findlistlambdaexpression ()
  59. {
  60. // Create a generic list class first
  61. List <string> List = new list <string> ();
  62. List. addrange (New String [] {"ASP. NET course", "J2EE course", "php course", "Data Structure Course "});
  63. // Here, lambda is used to create a delegate Method
  64. List <string> bookcategory = List. findall (string Str) => Str. endswith ("Course "));
  65. Foreach (string STR in bookcategory)
  66. {
  67. Console. writeline ("{0} \ t", STR );
  68. }
  69. }
  70.  
  71. }
  72. }

The running result of the program is 2-7.


 
Figure 2-7 running results
 

[Reprint] http://www.cnblogs.com/kingmoon/archive/2011/05/03/2035696.html

 

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.