您可以将Expression <Func <T,bool >>谓词传递到linq Where语句中吗?

qwe*_*234 2 c#

所以我有一个与此类似的方法:

public List<T> SomeFunction(Expression<Func<T, bool>> predicate) {
    return someList.Where(predicate).ToList();
}
Run Code Online (Sandbox Code Playgroud)

该代码不可编译,因为我无法将谓词传递给linq Where语句。有没有一种方法可以更改谓词以便与linq一起使用?

Ser*_*kiy 5

如果使用Enumerable.Where方法,则需要编译表达式

public List<T> SomeFunction(Expression<Func<T, bool>> predicate) {
    return someList.Where(predicate.Compile()).ToList();
}
Run Code Online (Sandbox Code Playgroud)

还要考虑您是否真的需要在这里使用表达式。你可以简单地通过Func<T, bool>