如何简化这样的语句:
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)
?
可以分多个步骤构造查询。
仅当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();