其他分享
首页 > 其他分享> > Linq.Expressions扩展ExpressionExtension

Linq.Expressions扩展ExpressionExtension

作者:互联网

    public static class ExpressionExtension
    {  
        public static Expression<Func<TSource, bool>> And<TSource>(this Expression<Func<TSource, bool>> a, Expression<Func<TSource, bool>> b)
        {
            ParameterExpression replaceWith = Expression.Parameter(typeof(TSource), "root");
            return Expression.Lambda<Func<TSource, bool>>(Expression.And(ParameterExpressionReplacer.Replace(a.Body, replaceWith), ParameterExpressionReplacer.Replace(b.Body, replaceWith)), new ParameterExpression[] { replaceWith });
        }
    
    }

    public class ParameterExpressionReplacer : ExpressionVisitor
    {
        // Fields
        private ParameterExpression replaceWith;
        private ParameterExpressionReplacer(ParameterExpression replaceWith)
        {
            this.replaceWith = replaceWith;
        }

        // Methods
        public static Expression Replace(Expression expression, ParameterExpression replaceWith) =>
            new ParameterExpressionReplacer(replaceWith).Visit(expression);

        protected override Expression VisitParameter(ParameterExpression node) =>
            replaceWith;

    }

标签:ExpressionExtension,ParameterExpressionReplacer,replaceWith,Linq,static,Paramete
来源: https://www.cnblogs.com/soraxtube/p/14291875.html