The use of C Lambda expressions is well understood

  • 2020-05-19 04:33:36
  • OfStack

If we want to extract the odd number of options from an integer array, there are many ways to do this. We understand the use of Lambda expressions by following three implementations

Method 1: name the method
 
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; 
} 
} 

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

Call:
 
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
 
var oddNums = Common.FilterArrayOfInt(nums, delegate(int i) { return i % 2 != 0; }); 

Method 3: Lambda expression
 
var oddNums = Common.FilterArrayOfInt(nums, i => i % 2 != 0); 

Obviously, using Lambda expressions makes the code cleaner.

Related articles: