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 语句判断查询方式。

 

相关文章:

  • 2021-08-05
  • 2022-01-26
  • 2021-12-04
  • 2021-07-31
  • 2021-08-04
  • 2021-12-15
  • 2021-07-08
猜你喜欢
  • 2022-12-23
  • 2021-05-28
  • 2022-12-23
  • 2021-12-02
  • 2021-06-24
相关资源
相似解决方案