NETCORE 合并多个Linq.Expression表达式

2021-05-08  本文已影响0人  醉酒的姑娘

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

//ImageOrder 表实例
Expression<Func<ImageOrder, bool>> expression = p=>true;
Expression<Func<ImageOrder, bool>> 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<Func<T, bool>> AndAlso<T>(
            this Expression<Func<T, bool>> expr1,
            Expression<Func<T, bool>> 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<Func<T, bool>>(
                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);
            }
        }
    }
上一篇下一篇

猜你喜欢

热点阅读