我需要将 lambda 查询作为参数传递,下面的代码是示例,我很想为它找到一个实现,有示例:像这样的东西:
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);
}
有人知道吗?
最佳答案
检查 Func(Of T, TResult) Delegate (MSDN)
using System;
public class LambdaExpression
{
public static void Main()
{
Func<string, string> convert = s => s.ToUpper();
string name = "Dakota";
Console.WriteLine(convert(name));
}
}
来自MSDN
The underlying type of a lambda expression is one of the generic Func delegates. This makes it possible to pass a lambda expression as a parameter without explicitly assigning it to a delegate. In particular, because many methods of types in the System.Linq namespace have Func(Of T, TResult) parameters, you can pass these methods a lambda expression without explicitly instantiating a Func(Of T, TResult) delegate.
编辑
您的案例的可能解决方案
static void Main(string[] args)
{
List<int> numbers = new List<int> { 10, 24, 9, 87, 193, 12, 7, 2, -45, -2, 9 };
Func<IEnumerable<int>, IEnumerable<int>> expr = n => n.Where(n1 => n1 > 6).OrderBy(n1 => n1 % 2 == 0).Select(n1 => n1);
UseLambda<int>(numbers, expr);
}
private static void UseLambda<T>(List<T> numbers,
Func<IEnumerable<T>,
IEnumerable<T>> expr)
{
var values = expr(numbers);
foreach (var item in values) {
Console.WriteLine(item);
}
}
关于c# - 有没有办法将 lambda 表达式作为变量或参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9063216/