using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace NFine.Code { public static partial class ExtLinq { public static Expression Property(this Expression expression, string propertyName) { return Expression.Property(expression, propertyName); } /// /// 先满足第一个,再满足第二个 /// /// /// /// public static Expression AndAlso(this Expression left, Expression right) { return Expression.AndAlso(left, right); } /// /// 调用参数 /// /// /// /// /// public static Expression Call(this Expression instance, string methodName, params Expression[] arguments) { return Expression.Call(instance, instance.Type.GetMethod(methodName), arguments); } /// /// 大于 /// /// /// /// public static Expression GreaterThan(this Expression left, Expression right) { return Expression.GreaterThan(left, right); } /// /// 大于等于 /// /// /// /// public static Expression GreaterThanOrEqual(this Expression left, Expression right) { return Expression.GreaterThanOrEqual(left, right); } /// /// 小于 /// /// /// /// public static Expression LessThan(this Expression left, Expression right) { return Expression.LessThan(left, right); } /// /// 小于等于 /// /// /// /// public static Expression LessThanOrEqual(this Expression left, Expression right) { return Expression.LessThanOrEqual(left, right); } public static Expression ToLambda(this Expression body, params ParameterExpression[] parameters) { return Expression.Lambda(body, parameters); } public static Expression> True() { return param => true; } public static Expression> False() { return param => false; } public static Expression> And(this Expression> first, Expression> second) { return first.Compose(second, Expression.AndAlso); } public static Expression> Or(this Expression> first, Expression> second) { return first.Compose(second, Expression.OrElse); } 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); var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); return Expression.Lambda(merge(first.Body, secondBody), first.Parameters); } private class ParameterRebinder : ExpressionVisitor { readonly Dictionary map; /// /// Initializes a new instance of the class. /// /// The map. ParameterRebinder(Dictionary map) { this.map = map ?? new Dictionary(); } /// /// Replaces the parameters. /// /// The map. /// The exp. /// Expression 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); } } } }