Convert Predicate<T> to Expression<Func<T, bool>>

ⅰ亾dé卋堺 提交于 2020-01-01 09:33:14

问题


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


回答1:


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.




回答2:


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));
}



回答3:


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 });
        }
    }
}


来源:https://stackoverflow.com/questions/9802269/convert-predicatet-to-expressionfunct-bool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!