方法一:命名方法
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;
}
}
调用:
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
}
方法二:匿名方法
var oddNums = Common.FilterArrayOfInt(nums, delegate(int i) { return i % 2 != 0; });
方法三:Lambda表达式
var oddNums = Common.FilterArrayOfInt(nums, i => i % 2 != 0);
很显然,使用Lambda表达式使代码更为简洁。