c#开发过程中,lambda表达式算是经常用到的东西;有时候需要 动态拼接lambda表达式用于查询之类的操作,这个时候就需要相应的封装类了。此类库简单易用,唯一需要注意的是在.netcore中,如果是复杂的查询条件用And方法拼接可能会报错,如果遇到And拼接报错;可以采用AndAlso拼接,具体原因不想去深究。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace CiCommon.Tools
{
    /// <summary>
    /// 拼接表达式树
    /// </summary>
    public static class LambdaExtensions
    {
        public static Expression<Func<T, bool>> True<T>() { return f => true; }
        public static Expression<Func<T, bool>> False<T>() { return f => false; }
        public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
        {
            // build parameter map (from parameters of second to parameters of first)
            var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);

            // replace parameters in the second lambda expression with parameters from the first
            var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);

            // apply composition of lambda expression bodies to parameters from the first expression
            return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
        }
        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.And);
        }
        public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.AndAlso);
        }
        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.Or);
        }

    }
    public class ParameterRebinder : ExpressionVisitor
    {
        private readonly Dictionary<ParameterExpression, ParameterExpression> map;

        public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
        {
            this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
        }

        public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
        {
            return new ParameterRebinder(map).Visit(exp);
        }

        protected override Expression VisitParameter(ParameterExpression p)
        {
            ParameterExpression replacement;
            if (map.TryGetValue(p, out replacement))
            {
                p = replacement;
            }
            return base.VisitParameter(p);
        }
    }

}

调用示例

Expression<Func<CommonJpFixUseless, bool>> expression = t => t.OrgId.Contains(orgid);
 //按需拼接表达式
if (!string.IsNullOrEmpty(orderCode))
                        {
                            expression = LambdaExtensions.And(expression, t => t.OrderCode.Contains(orderCode));
                        }
//将拼接好的表达式用于查询
var applyList = _unitOfWork.FixRepository.GetPage(expression);
最后修改:2022 年 09 月 29 日
如果觉得我的文章对你有用,请随意赞赏