【发布时间】:2020-06-28 20:04:48
【问题描述】:
我正在搜索一个 LINQ 查询,其中有 3 个参数,其中两个是可选参数,我为此编写了 if-else 条件,如下所示
if (id != null) { where condition}
else if (name!= null) { where condition }
else if (category != null) { where condition }
else if (id != null && name != null) { where condition }
else if (id != null && category != null) { where condition }
else if (name != null && category != null) {where condition}
else if (id != null && name != null && category != null ) { where condition }
如果再添加一个可选参数,我不想写更多的if-else条件
注意。 id 不是主键
【问题讨论】:
-
那是..有效?!?
-
无论如何,我想你可能正在寻找类似 Where(x => (q == null || x.q == q) && ..) 的东西;也就是说,防护装置移动到过滤器内部。否则 CHAIN 过滤器:f = ..; if (q != null) { f = f.Where(x => x.q == q); }
-
作为可选参数本身是无关紧要的。
标签: c# entity-framework linq asp.net-web-api