The expression <Func <in T, bool >> or the expression <Func <TBase, bool >> into the expression <Func <T, bool >> Converter

Is there an easy way to convert

Expression<Func<TBase,bool>> 

to

 Expression<Func<T,bool>> 

where does T inherit from TBase?

+4
source share
3 answers

As long as T comes from TBase, you can directly create an expression of your desired type with the body and parameters of your original expression.

 Expression<Func<object, bool>> x = o => o != null; Expression<Func<string, bool>> y = Expression.Lambda<Func<string, bool>>(x.Body, x.Parameters); 
+3
source

You may need to convert manually. The reason for this is because you are effectively converting into a subset of what it might be. All T are TBase , but not all TBase are T

The good news is that you can probably do this with Expression.Invoke and apply the corresponding conversion / conversion to TBase manually (of course, catching any security issues).

Edit: I apologize for not understanding which direction you wanted to go. I think just transforming an expression is still your best route anyway. This gives you the ability to handle the conversion, but you want to. Mark Gravel's answer here is the most compact and understandable way I've seen to do this.

+2
source

To do this, I wrote ExpressionVisitor with a VisitLambda and VisitParameter overload

Here he is:

 public class ConverterExpressionVisitor<TDest> : ExpressionVisitor { protected override Expression VisitLambda<T>(Expression<T> node) { var readOnlyCollection = node.Parameters.Select(a => Expression.Parameter(typeof(TDest), a.Name)); return Expression.Lambda(node.Body, node.Name, readOnlyCollection); } protected override Expression VisitParameter(ParameterExpression node) { return Expression.Parameter(typeof(TDest), node.Name); } } public class A { public string S { get; set; } } public class B : A { } static void Main(string[] args) { Expression<Func<A, bool>> ExpForA = a => aSStartsWith("Foo"); Console.WriteLine(ExpForA); // a => aSStartsWith("Foo"); var converter = new ConverterExpressionVisitor<B>(); Expression<Func<B, bool>> ExpForB = (Expression<Func<B, bool>>)converter.Visit(ExpForA); Console.WriteLine(ExpForB); // a => aSStartsWith("Foo"); - same as for A but for B Console.ReadLine(); } 
0
source

All Articles