1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| public static class QueryBuilder { public static Expression<Func<T, bool>> BuildPredicate<T>( string propertyName, object value, Operator op) { var param = Expression.Parameter(typeof(T), "x"); var property = Expression.Property(param, propertyName); var constant = Expression.Constant(value);
Expression body = op switch { Operator.Equals => Expression.Equal(property, constant), Operator.GreaterThan => Expression.GreaterThan(property, constant), Operator.LessThan => Expression.LessThan(property, constant), Operator.Contains => Expression.Call( property, "Contains", null, constant), _ => throw new NotSupportedException() };
return Expression.Lambda<Func<T, bool>>(body, param); }
public static Expression<Func<T, bool>> AndAlso<T>( this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right) { var param = Expression.Parameter(typeof(T), "x"); var body = Expression.AndAlso( Expression.Invoke(left, param), Expression.Invoke(right, param)); return Expression.Lambda<Func<T, bool>>(body, param); }
public static Expression<Func<T, bool>> OrElse<T>( this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right) { var param = Expression.Parameter(typeof(T), "x"); var body = Expression.OrElse( Expression.Invoke(left, param), Expression.Invoke(right, param)); return Expression.Lambda<Func<T, bool>>(body, param); } }
public enum Operator { Equals, GreaterThan, LessThan, Contains }
var pred1 = QueryBuilder.BuildPredicate<Product>("Price", 100, Operator.GreaterThan); var pred2 = QueryBuilder.BuildPredicate<Product>("Category", "电子", Operator.Equals); var combined = pred1.AndAlso(pred2);
var result = products.Where(combined.Compile()).ToList();
|