[英]How to convert an Expression<Func<T, bool>> to a Predicate<T>
I have a method that accepts an Expression<Func<T, bool>>
as a parameter. 我有一个接受
Expression<Func<T, bool>>
作为参数的方法。 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. 我想在List.Find()方法中将它用作谓词,但我似乎无法将其转换为List所采用的谓词。 Do you know a simple way to do this?
你知道一个简单的方法吗?
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();
}
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;
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();
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相同的IL
Func<T, bool> func = expression.Compile();
Predicate<T> predicate = func.Invoke;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.