前言

前两天在园子上看到一个问题

半年前我也思考过这些问题,但因为这样那样的问题,没有尝试去解决.

起初公司用上了 abp vnext ,而后有一部分代码能够这样写

protected override IQueryable<Resource> CreateFilteredQuery(GetResourceDto input){    return ReadOnlyRepository.WhereIf(        input.ParentId.HasValue,        item => item.ParentId == input.ParentId    ).WhereIf(        input.Id.HasValue,        item => item.Id == input.Id    );} 

用的时候感觉还是有点不便的,但没怎么思考过如何实现,也就这样始终用着了.

看到下面那个问题之后就想起来了这茬儿.

第一阶段

家喻户晓,去掉 if 的最简略的形式就是用三元 ()?():()

param = string.IsNullOrEmpty(x.CustomerID)        ?param        :param.And(x => x.CustomerID == query.CustomerID); 

讲道理,去掉了 if ,然而并没有感觉比用 if 的时候好多少

第二阶段

家喻户晓,感觉代码不难看(冗余多)的时候,你应该做点封装了

个别 来说,查问时用的应该是 IQueryable<T> Where(......)

所以能够对 IQueryable<T> 封装一些 简略 的扩大办法

public static class QueryClass{    public static IQueryable<T> WhereIf<T>(this IQueryable<T> query, bool flag, Expression<Func<T, bool>> expression)    {        return flag ? query.Where(expression) : query;    }    public static IQueryable<T> WhereIf<T>(this IQueryable<T> query, string flag, Expression<Func<T, bool>> expression)    {        return string.IsNullOrEmpty(flag) ? query : query.Where(expression);    }} 

用的时候就比较简单了

先定义一下(数据库)实体

public class Entity{    // 可为空    public Guid? Id { get; set; }    // 字符串    public string Name { get; set; }    // 值类型    public int Num { get; set; }} 

以上应该是程序外面用到的最多的3种数据类型了(大略)

而后整点数据

List<Entity> list = new(){    new Entity { Id = Guid.NewGuid(), Name = "2" },    new Entity { Id = Guid.NewGuid(), Name = "233333" },    new Entity { Id = Guid.NewGuid(), Name = "233333", Num = 233333 },    new Entity { Id = Guid.NewGuid(), Name = "233333", Num = 3 },    new Entity { Id = Guid.NewGuid(), Name = "23" },    ......    ......    new Entity { Id = Guid.NewGuid(), Name = "23", Num = 2333 },}; 

而后前端传了点数据过去

Entity input = new(){    Id = null,