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.