using System.Linq.Expressions; namespace DocumentServiceAPI.Utility { /// /// Lambda表达式拼接扩展类 /// public static class UtilitySearch { /// /// Lambda表达式拼接 /// /// /// /// /// /// public static Expression Compose(this Expression first, Expression second, Func merge) { // 构建参数映射(从第二个参数到第一个参数) var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f); // 将第二个lambda表达式中的参数替换为第一个lambda表达式的参数 var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); // 将lambda表达式体的组合应用于第一个表达式中的参数 return Expression.Lambda(merge(first.Body, secondBody), first.Parameters); } /// /// and扩展 /// /// /// /// /// public static Expression> And(this Expression> first, Expression> second) { return first.Compose(second, Expression.AndAlso); } /// /// or扩展 /// /// /// /// /// public static Expression> Or(this Expression> first, Expression> second) { return first.Compose(second, Expression.OrElse); } } /// /// /// public class ParameterRebinder : ExpressionVisitor { private readonly Dictionary map; /// /// /// /// public ParameterRebinder(Dictionary map) { this.map = map ?? new Dictionary(); } /// /// /// /// /// /// public static Expression ReplaceParameters(Dictionary 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); } } }