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 語句判斷查詢方式。