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)
谢谢
像这样吗
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)
从理论上讲,可以将委托“返回”转换为表达式,因为您可以请求发出的委托的IL,这将为您提供将其转换回所需的信息。
但是,这是出于一个原因,LINQ to SQL和Entity Framework都不这样做。这样做是复杂的,易碎的且性能密集的。
因此,简短的答案是,您无法将其转换为表达式。