using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace EC.Utils { /// /// ExtLinq /// 版 本:V3.0.0 /// 版 权:EasyCode /// 作 者:LXC /// public static partial class ExtLinq { public static Expression Property(this Expression expression, string propertyName) { return Expression.Property(expression, propertyName); } 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> ToLambda(string propertyName, string propertyValue) { var parameter = Expression.Parameter(typeof(T), "t"); return Expression.Lambda>(Expression.Equal(parameter.Property(propertyName), Expression.Constant(propertyValue)), parameter); } public static Expression ToLambda(this Expression body, params ParameterExpression[] parameters) { return Expression.Lambda(body, parameters); } 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); } public static string GetPropertyName(Expression> expression) { var name = ""; if (expression.Body is UnaryExpression) { name = ((MemberExpression)((UnaryExpression)expression.Body).Operand).Member.Name; } else if (expression.Body is MemberExpression) { name = ((MemberExpression)expression.Body).Member.Name; } else if (expression.Body is ParameterExpression) { name = ((ParameterExpression)expression.Body).Type.Name; } return name; } private static bool IsNullableType(Type theType) { return (theType.IsGenericType && theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))); } private class ParameterRebinder : ExpressionVisitor { private readonly Dictionary map; /// /// Initializes a new instance of the class. /// /// The map. private 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); } } } }