记录一次使用 Expression 的方法
/// <summary> /// 实现 Name == "a" or Name == "b" or Name == "c" /// </summary> /// <typeparam name="T"></typeparam> /// <param name="query"></param> /// <param name="condition"></param> /// <param name="selector"></param> /// <param name="values"></param> /// <returns></returns> public static IQueryable<T> WhereIfEqOr<T, TResult>(this IQueryable<T> query, bool condition, Expression<Func<T, TResult>> selector, List<TResult> values) { if (condition == false) return query; if (values != null && values.Count > 0) { Type type = typeof(T); ParameterExpression paramExp = Expression.Parameter(type, "x"); var memberExp = selector.Body as MemberExpression; Expression propertyExp = Expression.Property(paramExp, memberExp.Member.Name); Expression expression = Expression.Equal(propertyExp, Expression.Constant(values[0], typeof(TResult))); for (int i = 1; i < values.Count; i++) { expression = Expression.Or(expression, Expression.Equal(propertyExp, Expression.Constant(values[i], typeof(TResult)))); } var lambda = Expression.Lambda<Func<T, bool>>(expression, paramExp); query = query.Where(lambda); } return query; }
/// <summary> /// 实现 Name like "%a%" or Name like "%b%" or Name like "%c%" /// </summary> /// <typeparam name="T"></typeparam> /// <param name="query"></param> /// <param name="condition"></param> /// <param name="selector"></param> /// <param name="values"></param> /// <returns></returns> public static IQueryable<T> WhereIfContainsOr<T, TResult>(this IQueryable<T> query, bool condition, Expression<Func<T, TResult>> selector, List<TResult> values) { if (condition == false) return query; if (values != null && values.Count > 0) { Type type = typeof(T); ParameterExpression paramExp = Expression.Parameter(type, "x"); var memberExp = selector.Body as MemberExpression; Expression propertyExp = Expression.Property(paramExp, memberExp.Member.Name); Expression expression = Expression.Call(propertyExp, typeof(string).GetMethod("Contains", new Type[] { typeof(string) }), Expression.Constant(values[0], typeof(TResult))); for (int i = 1; i < values.Count; i++) { expression = Expression.Or(expression, Expression.Call(propertyExp, typeof(string).GetMethod("Contains", new Type[] { typeof(string) }), Expression.Constant(values[i], typeof(TResult)))); } var lambda = Expression.Lambda<Func<T, bool>>(expression, paramExp); query = query.Where(lambda); } return query; }
这两种方法可以使用一个字段的或关系