Convert Predicate to Expression>

2019-04-08 01:24发布

Is possible to convert a Predicate<T> to Expression<Func<T, bool>> in some way?

I would like to use the next IQueryable function using the filters of the my ICollectionView:

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

Thanks

3条回答
小情绪 Triste *
2楼-- · 2019-04-08 01:39
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 });
        }
    }
}
查看更多
萌系小妹纸
3楼-- · 2019-04-08 01:45

Something like this?

Predicate<string> predicate = input => input.Length > 0;
Expression<Func<string, bool>> expression = (input) => predicate(input);

You can probably make an extension Where method for your ICollectionView which takes a predicate, converts it to an Expression like this, and then call the Where method provided by Linq.

public static IQueryable<T> Where(this IQueryable<T> source, Predicate<T> predicate)
{
    return source.Where(x => predicate(x));
}
查看更多
狗以群分
4楼-- · 2019-04-08 02:01

In theory it is possible to convert a delegate 'back' to an expression, because you can request the emitted IL of a delegate, which gives you the information you need to transform it back.

However, it's for a reason that neither LINQ to SQL and Entity Framework do this. It is complex, fragile, and performance intensive to do so.

So the short answer is, you can't transform it to an expression.

查看更多
登录 后发表回答