Convert predicate <T> to expression <Func <T, bool >>

Is there any way to convert a Predicate<T> to Expression<Func<T, bool>> ?

I would like to use the following IQueryable function using the filters of 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

+6
source share
3 answers

In theory, you can convert a delegate back to an expression because you can request an emitted delegate IL that gives you the information you need to convert it.

However, for the reason that neither LINQ to SQL nor Entity Framework do this. This is a complex, fragile and high-performance process.

So the short answer is: you cannot convert it to an expression.

+2
source

Something like that?

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

Perhaps you can make a Where extension method for your ICollectionView, which takes a predicate, converts it to an expression that way, and then calls the Where method provided by Linq.

 public static IQueryable<T> Where(this IQueryable<T> source, Predicate<T> predicate) { return source.Where(x => predicate(x)); } 
+2
source
 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 }); } } } 
+1
source

Source: https://habr.com/ru/post/911280/


All Articles