将谓词转换为表达式<Func >

有可能以某种方式将Predicate to Expression<Func>转换Predicate to Expression<Func>吗?

我想使用我的ICollectionView的filter来使用下一个IQueryable函数:

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

谢谢

从理论上讲,可以将委托“后退”转换为表达式,因为您可以请求委托的发出的IL,从而为您提供转换它所需的信息。

但是,这是因为LINQ to SQL和Entity Framework都没有这样做。 这样做复杂,脆弱且性能密集。

所以简短的回答是,你无法将其转换为表达式。

像这样的东西?

 Predicate predicate = input => input.Length > 0; Expression> expression = (input) => predicate(input); 

你可以创建一个扩展名为ICollectionView的方法,它接受一个谓词,将它转换为这样的表达式,然后调用Linq提供的Where方法。

 public static IQueryable Where(this IQueryable source, Predicate predicate) { return source.Where(x => predicate(x)); } 
 namespace ConsoleApplication1 { static class Extensions { public static Expression> ToExpression(this Predicate p) { ParameterExpression p0 = Expression.Parameter(typeof(T)); return Expression.Lambda>(Expression.Call(p.Method, p0), new ParameterExpression[] { p0 }); } } }