将谓词<T>转换为表达式<Func <T,bool >>

Mar*_*aut 7 c# expression predicate iqueryable icollectionview

有可能以Predicate<T> to Expression<Func<T, bool>>某种方式转换?

我想使用我的ICollectionView的过滤器使用下一个IQueryable函数:

public static System.Linq.IQueryable<TSource> Where<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate)
Run Code Online (Sandbox Code Playgroud)

谢谢

Jes*_*sen 5

像这样吗

Predicate<string> predicate = input => input.Length > 0;
Expression<Func<string, bool>> expression = (input) => predicate(input);
Run Code Online (Sandbox Code Playgroud)

您可以Where为ICollectionView 制作一个扩展方法,该方法采用一个谓词,将其转换为这样的Expression,然后调用Linq提供的Where方法。

public static IQueryable<T> Where(this IQueryable<T> source, Predicate<T> predicate)
{
    return source.Where(x => predicate(x));
}
Run Code Online (Sandbox Code Playgroud)

  • -1:在表达式未执行但在LINQ to SQL,LINQ to EF,LINQ to NHibernate等中进行分析的情况下,这并非在所有情况下都有效。 (4认同)

Ste*_*ven 5

从理论上讲,可以将委托“返回”转换为表达式,因为您可以请求发出的委托的IL,这将为您提供将其转换回所需的信息。

但是,这是出于一个原因,LINQ to SQL和Entity Framework都不这样做。这样做是复杂的,易碎的且性能密集的。

因此,简短的答案是,您无法将其转换为表达式。