有什么方法可以将lambda表达式作为变量或参数传递? [英] Is there any way to pass the lambda expression as a variable or argument?
本文介绍了有什么方法可以将lambda表达式作为变量或参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将lambda查询作为参数传递,以下代码为示例,我很高兴为它找到一个实现,有示例:像这样的东西:
I need to pass the lambda query as a parameter, the followings code is sample and I am interesting to find an implement for it, there is samples: some thing like this:
var expr1 = Where(n => n > 6).OrderBy(n => n % 2 == 0).Select(n => n);
var expr2 = TakeWhile((n, index) => n >= index));
并像这样使用它:
public void UseLambda<T> (IEnumerable<T> source , lambda Expr){
var items= Expr.Compile(source);
foreach(var item in items)
Console.Writeline(item.ToString());
}
public void Main(){
List<int> numbers = new List<int> { 10, 24, 9, 87, 193, 12, 7, 2, -45, -2, 9 };
var expr1 = Where(n => n > 6).OrderBy(n => n % 2 == 0).Select(n => n);
UseLambda(numbers, expr1);
}
有人对此有想法吗?
推荐答案
如果您这样定义LINQ表达式:
If you define your LINQ expressions like this:
Func<IEnumerable<int>, IEnumerable<int>> expr1 =
l => l.Where(n => n > 6).OrderBy(n => n % 2 == 0).Select(n => n);
Func<IEnumerable<int>, IEnumerable<int>> expr2 =
l => l.TakeWhile((n, index) => n >= index);
您的UseLambda方法如下:
And your UseLambda method as:
public void UseLambda<T> (IEnumerable<T> source
,Func<IEnumerable<T>, IEnumerable<T>> lambda)
{
var items= lambda(source);
foreach(var item in items)
Console.Writeline(item.ToString());
}
}
那你我想你有想要的东西.
Then you I think you have what you're looking for.
这篇关于有什么方法可以将lambda表达式作为变量或参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文