C# 如何将 Expression<Func<T, bool>> 转换为 Predicate<T>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1217749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 13:47:31  来源:igfitidea点击:

How to convert an Expression<Func<T, bool>> to a Predicate<T>

c#expressionpredicate

提问by Lance Fisher

I have a method that accepts an Expression<Func<T, bool>>as a parameter. I would like to use it as a predicate in the List.Find() method, but I can't seem to convert it to a Predicate which List takes. Do you know a simple way to do this?

我有一个接受 anExpression<Func<T, bool>>作为参数的方法。我想将它用作 List.Find() 方法中的谓词,但我似乎无法将其转换为 List 采用的谓词。你知道一个简单的方法来做到这一点吗?

public IList<T> Find<T>(Expression<Func<T, bool>> expression) where T : class, new()
{
    var list = GetList<T>();

    var predicate = [what goes here to convert expression?];

    return list.Find(predicate);
}

Update

更新

Combining answers from tvanfosson and 280Z28, I am now using this:

结合 tvanfosson 和 280Z28 的答案,我现在正在使用这个:

public IList<T> Find<T>(Expression<Func<T, bool>> expression) where T : class, new()
{
    var list = GetList<T>();

    return list.Where(expression.Compile()).ToList();
}

采纳答案by Sam Harwell

Func<T, bool> func = expression.Compile();
Predicate<T> pred = t => func(t);

Edit: per the comments we have a better answer for the second line:

编辑:根据评论,我们对第二行有更好的答案:

Predicate<T> pred = func.Invoke;

回答by tvanfosson

I'm not seeing the need for this method. Just use Where().

我不认为需要这种方法。只需使用 Where()。

 var sublist = list.Where( expression.Compile() ).ToList();

Or even better, define the expression as a lambda inline.

或者更好的是,将表达式定义为 lambda 内联。

 var sublist = list.Where( l => l.ID == id ).ToList();

回答by Jon Skeet

Another options which hasn't been mentioned:

另一个没有提到的选项:

Func<T, bool> func = expression.Compile();
Predicate<T> predicate = new Predicate<T>(func);

This generates the same IL as

这会生成与以下相同的 IL

Func<T, bool> func = expression.Compile();
Predicate<T> predicate = func.Invoke;