简体   繁体   English

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

[英]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.

相关问题 转换谓词 <T> 表达 <Func<T, bool> &gt; - Convert Predicate<T> to Expression<Func<T, bool>> 如何转换Func <T, bool> 谓词 <T> ? - How to convert Func<T, bool> to Predicate<T>? 如何转换Func <T,bool> 表达 <Func<T,bool> &gt; - How to convert Func<T,bool> to Expression<Func<T,bool>> 表达<Func<T, bool> &gt; 谓词两种类型 - Expression<Func<T, bool>> predicate two types 如何传递表达式<Func<T, bool> &gt; 谓词作为方法的参数? - How to pass Expression<Func<T, bool>> predicate as a parameter to a method? 转换表达式 <Func<T,T,bool> &gt;表达 <Func<T,bool> &gt; - Convert Expression<Func<T,T,bool>> to Expression<Func<T,bool>> 如何将简单的视图模型转换为Func <T,bool> 谓语? - How to convert a simple viewmodel to Func<T,bool> predicate? 我可以动态创建一个表达式 <Func<T, bool> &gt;谓词,但我如何创建表达式 <Func<T1,T2,bool> &gt; - I can dynamically create an Expression<Func<T, bool>> predicate ,but how do i create Expression<Func<T1,T2,bool>> 是否可以转换表达式 <Func<T, bool> &gt;表达 <Func<MyType, bool> &gt;? - Is it possible to convert Expression<Func<T, bool>> to Expression<Func<MyType, bool>>? 如何转换表达式 <Func<T1, bool> &gt;表达 <Func<T2, bool> &gt; - How to convert Expression<Func<T1, bool>> to Expression<Func<T2, bool>>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM