【问题标题】:Combine multiple where conditions having optional parameters in C# linq?在 C# linq 中结合多个具有可选参数的 where 条件?
【发布时间】: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


【解决方案1】:

EF 中的最佳模式是仅有条件地添加 Where 条件。 EG

IQueryable<SomeType> qry = ...;
if (id != null)
{
  qry = qry.Where(x => x.Id == id);
}
if (name != null)
{
  qry = qry.Where(x => x.Name == name);
}
if (category != null)
{
  qry = qry.Where(x => x.Category == category);
}
var results = qry.ToList();

这样你就不会用许多不做任何事情的谓词弄乱表达式,但这会弄乱查询执行。

【讨论】:

    【解决方案2】:

    你可以这样写

    id == null ? true : {id condition} &&
    name == null ? true : {name condition} &&
    category == null ? true: {category } and other conditions
    

    或者

    id == null || {id condition} &&
    id == null || {id condition} &&
    

    如果它的值等于 null,则返回 true 将使语句为 true。 它干净,易于理解和开发。

    希望对你有帮助。

    【讨论】:

      【解决方案3】:

      我总是在下面做。易于阅读和记忆。

      myList
          .Where(x => id == null || x.Id == id)
          .Where(x => name == null || x.Name == name)
          .Where(x => category == null || x.Category == category);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-19
        • 1970-01-01
        • 1970-01-01
        • 2017-05-06
        • 2013-06-25
        • 1970-01-01
        相关资源
        最近更新 更多