【发布时间】:2020-11-19 16:02:07
【问题描述】:
我有多个输入参数,我想在 where 子句中检查,但我只想检查参数是否为空。如果它不为 null,那么我不希望该参数出现在 where 子句中。
目前的工作方式如下:
if(userId != null){
list.Where(x=> x.Id == id && x.UserId == userId);
}
else{
list.where(x=> x.Id == id)
}
如果我们有多个可以为 null 或不为 null 的参数,这是不可行的,因为它会创建嵌套的 if 条件。这里最好的解决方案是什么?
【问题讨论】:
-
list.Where(x=> x.Id == id && (userId == null || x.UserId == userId))或var query = list.where(x=> x.Id == id)然后query = userId != null ? query.Where(x.UserId == userId) : query;