相关文章推荐
强健的大葱  ·  自訂日期格式 - Tableau·  3 周前    · 
傻傻的大蒜  ·  jsoncpp 创建数组-掘金·  2 年前    · 
刚毅的香烟  ·  反射创建枚举-掘金·  2 年前    · 
public static class QueryableExtensions
    public static IQueryable<T> WhereIf<T>(this IQueryable<T> query, bool condition, Expression<Func<T, bool>> predicate)
        return condition ? query.Where(predicate) : query;
    public static IQueryable<T> WhereIf<T>(this IQueryable<T> query, bool condition, Expression<Func<T, int, bool>> predicate)
        return condition ? query.Where(predicate) : query;
    public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> query, bool condition, Func<T, bool> predicate)
        return condition ? query.Where(predicate) : query;

  上面类中扩展了 IQueryable 与 IEnumerable 两种数据类型的方法。使用方式如下:

repository.IQueryable<DP_Project>().WhereIf(type > 0, x => x.Type == type);

这样就替代了原来通过 if 语句判断查询方式。