可以某种方式转换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)
由于
答案 0 :(得分:5)
这样的东西?
Predicate<string> predicate = input => input.Length > 0;
Expression<Func<string, bool>> expression = (input) => predicate(input);
你可以为你的ICollectionView创建一个扩展Where
方法,它接受一个谓词,将它转换为这样的表达式,然后调用Linq提供的Where方法。
public static IQueryable<T> Where(this IQueryable<T> source, Predicate<T> predicate)
{
return source.Where(x => predicate(x));
}
答案 1 :(得分:5)
理论上,可以将委托'back'转换为表达式,因为您可以请求委托的发出IL,它为您提供转换它所需的信息。
然而,这是因为LINQ to SQL和Entity Framework都没有这样做。这样做复杂,脆弱,性能密集。
所以简短的回答是,你不能将它转换成表达式。
答案 2 :(得分:1)
namespace ConsoleApplication1
{
static class Extensions
{
public static Expression<Func<T, bool>> ToExpression<T>(this Predicate<T> p)
{
ParameterExpression p0 = Expression.Parameter(typeof(T));
return Expression.Lambda<Func<T, bool>>(Expression.Call(p.Method, p0),
new ParameterExpression[] { p0 });
}
}
}