C # lambda Expression Purpose Deep Understanding _ practical skills

Source: Internet
Author: User
If we want to remove the odd-numbered option from an integer array, there are a number of implementations, and we understand the use of lambda expressions in the following three ways of implementing

method One: Naming methods
Copy Code code as follows:

public class Common
{
Public delegate bool Intfilter (int i);
public static list<int> Filterarrayofint (int[] ints, Intfilter filter)
{
var lstoddint = new list<int> ();
foreach (var i in ints)
{
if (filter (i))
{
Lstoddint.add (i);
}
}
return lstoddint;
}
}

Copy Code code as follows:

public class Application
{
public static bool IsOdd (int i)
{
Return i% 2!= 0;
}
}

Call:
Copy Code code as follows:

var nums = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var oddnums = Common.filterarrayofint (Nums, application.isodd);
foreach (var item in oddnums)
{
Console.WriteLine (item); 1,3,5,7,9
}

method Two: Anonymous method
Copy Code code as follows:

var oddnums = Common.filterarrayofint (Nums, delegate (int i) {return I% 2!= 0;});

method Three: lambda expression
Copy Code code as follows:

var oddnums = Common.filterarrayofint (nums, I => i% 2!= 0);

Clearly, using lambda expressions makes your code simpler.

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.