If we want to retrieve an odd number of options from an integer array, there are many implementation methods. We use the following three implementation methods to compare and understand the usage of Lambda expressions.
Method 1: naming method Copy codeThe Code is 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 codeThe Code is as follows: public class Application
{
Public static bool IsOdd (int I)
{
Return I % 2! = 0;
}
}
Call:Copy codeThe Code is 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 2: anonymous method Copy codeThe Code is as follows: var oddNums = Common. FilterArrayOfInt (nums, delegate (int I) {return I % 2! = 0 ;});
Method 3: Lambda expressions Copy codeThe Code is as follows: var oddNums = Common. FilterArrayOfInt (nums, I => I % 2! = 0 );
Obviously, using Lambda expressions makes the code more concise.