Passing a binary expression as a parameter

public static Expression<Func<T, bool>> OrElse<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { ParameterExpression parameter = Expression.Parameter(typeof(T)); ReplaceExpressionVisitor leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter); Expression left = leftVisitor.Visit(expr1.Body); ReplaceExpressionVisitor rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter); Expression right = rightVisitor.Visit(expr2.Body); return Expression.Lambda<Func<T, bool>>(Expression.OrElse(left, right), parameter); } 

Since I have another method where the only difference is the expression in the return statement, how do I pass Expression.OrElse as a parameter to the method (my other method uses AndAlso )?

Since the methods are close to identical, I need one common method with an expression passed as a parameter.

I tried to skip BinaryExpression without success.

+6
source share
1 answer

How about this?

 public static Expression<Func<T, bool>> BinaryOp<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2, Func<Expression, Expression, BinaryExpression> operation) { ParameterExpression parameter = Expression.Parameter(typeof(T)); ReplaceExpressionVisitor leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter); Expression left = leftVisitor.Visit(expr1.Body); ReplaceExpressionVisitor rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter); Expression right = rightVisitor.Visit(expr2.Body); return Expression.Lambda<Func<T, bool>>(operation(left, right), parameter); } public static Expression<Func<T, bool>> OrElse<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { return BinaryOp(expr1, expr2, Expression.OrElse); // passed as mth group } public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { return BinaryOp(expr1, expr2, Expression.AndAlso); // passed as mth group } 
+6
source

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


All Articles