Combining two expressions (Expression>)

前端 未结 7 1538
无人共我
无人共我 2020-11-22 01:09

I have two expressions of type Expression> and I want to take to OR, AND or NOT of these and get a new expression of the same type

7条回答
  •  孤独总比滥情好
    2020-11-22 01:41

    I needed to achieve the same results, but using something more generic (as the type was not known). Thanks to marc's answer I finally figured out what I was trying to achieve:

        public static LambdaExpression CombineOr(Type sourceType, LambdaExpression exp, LambdaExpression newExp) 
        {
            var parameter = Expression.Parameter(sourceType);
    
            var leftVisitor = new ReplaceExpressionVisitor(exp.Parameters[0], parameter);
            var left = leftVisitor.Visit(exp.Body);
    
            var rightVisitor = new ReplaceExpressionVisitor(newExp.Parameters[0], parameter);
            var right = rightVisitor.Visit(newExp.Body);
    
            var delegateType = typeof(Func<,>).MakeGenericType(sourceType, typeof(bool));
            return Expression.Lambda(delegateType, Expression.Or(left, right), parameter);
        }
    

提交回复
热议问题