C#中如何让lambda表达式返回另一个lambda表达式?lambda表达式可以传递么?
可以啊。lambda本身也是一个类型,所以也可以返回:
Func<int, bool> MyAnd(Func<int, bool> f1, Func<int, bool> f2)
{
return x => f1(x) && f2(x);
}
调用
Func<int, bool> f1 = x => x < 10;
Func<int, bool> f2 = x => x % 2 == 0;
int[] data = { 1, 2, 3, 4, 5, 8, 9, 11, 12, 14 };
var query = data.Where(MyAnd(f1, f2)); // 输出 2 4 8
int[] arr = { 1, 2, 3, 4, 5, 8, 9, 11, 12, 14 };
Func<int, bool> f1 = x => x < 10;
Func<int, bool> f2 = x => x % 2 == 0;
Func<int, bool> myand = x => f1(x) && f2(x);
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]+" "+ myand(i));
}