C#LAMBDA-expression

Source: Internet
Author: User

Transfer from https://www.cnblogs.com/kingmoon/archive/2011/05/03/2035696.html

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:

    1. delegate int del (int i);
    2. del mydelegate = x => x * x;
    3. 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.

  1. public class people
  2. {
  3. public int Age {get; set;} Setting properties
  4. public string name {get; set;} Setting properties
  5. Public people (int age,string name)//Set Property (constructor construct)
  6. {
  7. this.age = age; Initialize the property value of age
  8. this.name = name; Initialize property value name
  9. }
  10. }

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.

  1. List<people> people = new List<people> (); Creating generic Objects
  2. People P1 = New People ("guojing"); Create an Object
  3. People P2 = New People ("Wujunmin"); Create an Object
  4. People p3 = New People ("muqing"); Create an Object
  5. People P4 = New People (at "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 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 >;});

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.

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

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

  1. (x, y) => x * Y//multi-parameter, 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 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.

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

  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 Delegate 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 using lambda:");
  18. Findlistlambdaexpression ();
  19. }
  20. Example of a traditional invocation delegate
  21. static void Findlistdelegate ()
  22. {
  23. First, create a generic list class
  24. List<string> list = new list<string> ();
  25. List. AddRange (new string[] {"ASP. NET course, "EE course", "PHP Course", "Data Structure Course"});
  26. predicate<string> findpredicate = new predicate<string> (  Isbookcategory);
  27. List<string> bookcategory = list.  FindAll (findpredicate);
  28. foreach (String str in bookcategory)
  29. {
  30. Console.WriteLine ("{0}\t", str);
  31. }
  32. }
  33. predicate method, this method will be passed to the FindAll method to determine the classification of books and books
  34. static bool Isbookcategory (String str)
  35. {
  36. Return str. EndsWith ("course")? True:false;
  37. }
  38. Using anonymous methods for the search process
  39. static void Findlistanonymousmethod ()
  40. {
  41. First, create a generic list class
  42. List<string> list = new list<string> ();
  43. List. AddRange (new string[] {"ASP. NET course, "EE course", "PHP Course", "Data Structure Course"});
  44. Here, the anonymous method is used to create a block of code directly for the delegate without having to create a separate method
  45. List<string> bookcategory = list. FindAll
  46. (Delegate (String str)
  47. {
  48. Return str. EndsWith ("course")? True:false;
  49. }
  50. );
  51. foreach (String str in bookcategory)
  52. {
  53. Console.WriteLine ("{0}\t", str);
  54. }
  55. }
  56. Using lambda to implement the search process
  57. static void Findlistlambdaexpression ()
  58. {
  59. First, create a generic list class
  60. List<string> list = new list<string> ();
  61. List. AddRange (new string[] {"ASP. NET course, "EE course", "PHP Course", "Data Structure Course"});
  62. Here, Lambda is used to create a delegate method
  63. List<string> bookcategory = list. FindAll (string str) => str.  EndsWith ("course"));
  64. foreach (String str in bookcategory)
  65. {
  66. Console.WriteLine ("{0}\t", str);
  67. }
  68. }
  69. }
  70. }

The program's run results are shown in 2-7.

Figure 2-7 Running Results

C#LAMBDA-expression

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.