NETCORE 合并多个Linq.Expression表达式

需求sql: select .. from .. where (id=1 or id=2 or id=3) and name='liuxiaolei'

//ImageOrder 表实例
Expression> expression = p=>true;
Expression> expressionMember = p => false;

//表达式2 进行or拼接
foreach (var info in MemberList)
{
    expressionMember=expressionMember.Or(p => p.id== info.id);
}
//表达式1 进行and拼接
expression = expression.And(p => p.name.Contains(name));

//合并Expression表达式
var ExpressionCombine = ExpressHelper.AndAlso(expression, expressionMember);

    //Combine Expression表达式
    public static class ExpressHelper {
        public static Expression> AndAlso(
            this Expression> expr1,
            Expression> expr2)
        {
            var parameter = Expression.Parameter(typeof(T));

            var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
            var left = leftVisitor.Visit(expr1.Body);

            var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
            var right = rightVisitor.Visit(expr2.Body);
            //expr2为or拼接的表达式,若为false 则不拼接直接返回expr1表达式
            if (expr2.Body.ToString() == "False") {
                return expr1;
            }
            return Expression.Lambda>(
                Expression.AndAlso(left, right), parameter);
        }



        private class ReplaceExpressionVisitor
            : ExpressionVisitor
        {
            private readonly Expression _oldValue;
            private readonly Expression _newValue;

            public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
            {
                _oldValue = oldValue;
                _newValue = newValue;
            }

            public override Expression Visit(Expression node)
            {
                if (node == _oldValue)
                    return _newValue;
                return base.Visit(node);
            }
        }
    }

你可能感兴趣的:(NETCORE 合并多个Linq.Expression表达式)