C #3.0 highlights-lambda expressions

Source: Internet
Author: User

Before C #2.0, if a method or variable needs to use a delegate, you must create a naming method and input the name at the place where the delegate is required. for example, a data processing method for int type is used to filter out an odd element in an int array or some other elements that meet the conditions...

00 public class Commom

01 {

02 // name a delegate Method

03 public delegate bool IntFilter (int I );

04 // filter out the int that meets the requirements of the delegate method, and return an int []

05 public static int [] FilterArrayOfInts (int [] ints, IntFilter filter)

06 {

07 ArrayList aList = new ArrayList ();

08 foreach (int I in ints)

09 if (filter (I ))

10 aList. Add (I );

11 return (int []) aList. ToArray (typeof (int ));

12}

13}

The Commom class establishes a unified model, which is mainly used to pass in a delegate method and obtain the numbers required by the conditions of the delegate method. the specific delegate method can be written in another class. Many methods can be written to check whether it is an odd number, an even number, or a multiple of 3... write this as needed. this improves the reusability of the Commom class.

00 // define the filtering method as needed

01 public class MyIntFilter

02 {

03 // custom Filtering Method 1: Check whether it is an odd number

04 public static bool IsOdd (int I)

05 {

06 return (I & 1) = 1 );

07}

08 // custom Filtering Method 2: Check whether the filter is an even number.

09 public static bool IsEven (int I)

10 {

11 return (I & 1 )! = 1 );

12}

13 //... Other filtering methods can be defined as needed

14}

Call the filtering method in MyIntFilter:

00 int [] nums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

01 // filtering is surprising

02 int [] oddNums = Commom. FilterArrayOfInts (nums, MyIntFilter. IsOdd );

03 // filter out even numbers

04 int [] evenNums = Commom. FilterArrayOfInts (nums, MyIntFilter. IsEven );

05 // Test Result: oddNums and evenNums are printed.

06 Console. WriteLine ("Print oddNums :");

07 foreach (int I in oddNums)

08 Console. Write (I + "");

09 Console. WriteLine ("Print evenNums :");

10 foreach (int I in evenNums)

11 Console. Write (I + "");

Use the "anonymous method" to implement lambda functions (Since C #2.0)
Why use the anonymous method? A: You are lazy. writing a method for each filtering policy is often annoying. Many methods may only be used once or twice, in addition, it is unpleasant to set a nice name for each method and input these method names when calling these methods, therefore, you can use the "anonymous Method" in C #2.0 to solve this problem:

0 int [] nums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

1 // returns a surprising amount of data.

2 int [] oddNums = Commom. FilterArrayOfInts (nums, delegate (int I)

3 {

4 return (I & 1) = 1 );

5 });

6 Console. WriteLine ("Print oddNums :");

7 foreach (int I in oddNums)

8 Console. Write (I + "");

In this case, all the odd numbers in the int array are filtered out, instead of using the MyIntFilter class to determine whether it is an odd number. The advantage of this anonymous method is that it saves the effort to maintain the context in the program code.

Use lambda expressions (Since C #3.0)
Lambda expressions are in the following format:

0 (param1, param2, param3. ..) => {doSomethingWithParam1, doSomethingWithParam2, doSomethingWithParam3 ...}

What are the benefits of lambda? The most important function may be to improve readability and make it concise and clear. You only need to list the parameters that need to be used in the method body, and then add =>{} to write the method body in braces. however, note that the input parameter type must meet the input type defined previously by delegate and return the return type defined by delegate.

Similarly, the preceding requirement is that you can filter out the surprising numbers from the int array and use the lambda expression to write as follows:

0 int [] nums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

1 // returns a surprising amount of data.

2 int [] oddNums = Commom. FilterArrayOfInts (nums, (I) => (I & 1) = 1 ));

3 foreach (int I in oddNums)

4 Console. Write (I + "");

When to use lambda expressions
By comparing the three methods, we can find that lambda expressions are the most concise. however, not all such cases use lambda expressions. for complex algorithms that need to be reused, it is best to use the first "naming method", because in this way, any developer can easily directly call the method at any time, you do not need to consider these details.

C #3.0 many new features almost all imply that the service is for Linq, and Lambda expressions are no exception, because a Linq query usually only needs to be called once, you do not need to name a method for each query.

Author: Create Chen

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.