简化if语句

本文关键字:语句 if 简化 | 更新日期: 2023-09-27 17:49:42

如何简化这样的语句:

    var someList = new List<someType>();
    if (String.IsNullOrEmpty(groupId))
    {
        someList = CTX.Values.Include(c => c.Customer).ToList();
    }
    else
    {
        someList = CTX.Values.Include(c => c.Customer).Where(c => c.GroupId== groupId).ToList();
    }

差异仅存在于.Where(c => c.GroupId== groupId)。是否可以在查询语句中包含条件String.IsNullOrEmpty(groupId) ?

简化if语句

可以分多个步骤构造查询。

仅当groupId不为空时添加Where部分。

查询只会在调用ToList()后执行。

var values = CTX.Values.Include(c => c.Customer);
if(!String.IsNullOrEmpty(groupId))
  values = values.Where(c => c.GroupId == groupId);
someList = values.ToList();

也许是这个?

someList = CTX.Values.Include(c => c.Customer)
       .Where(c => String.IsNullOrEmpty(groupId)
                   || c.GroupId== groupId)
       .ToList();

bool isGroupValid = String.IsNullOrEmpty(groupId);
someList = CTX.Values.Include(c => c.Customer)
       .Where(c => isGroupValid
               || c.GroupId== groupId)
       .ToList();

您可以添加:

.Where(c => String.IsNullOrEmpty(groupId))

:

CTX.Values.Include(c => c.Customer)
    .Where(c => c.GroupId == groupId || c => String.IsNullOrEmpty(groupId))
    .ToList();