【问题标题】:Use variable in where clause only if NOT empty? A kind of dynamic where clause?仅当非空时才在 where 子句中使用变量?一种动态的where子句?
【发布时间】:2011-05-11 17:24:39
【问题描述】:

是否可以在 where (LINQ) 中包含一个子句,但前提是它的“NOT”为空?

  where c.Code == sCode && p.Code == code

在这种情况下,变量(标准 c#)被称为代码......如果它不是空的,那么上面的 where 很好......但是如果它是空的,那么我不想在其中包含 where

  where c.Code == sCode

在 SQL 中是这样完成的

       AND ( ( @code = '' )
                  OR ( @code <> ''
                       AND C.Code = @code
                     )

【问题讨论】:

    标签: linq dynamic where-clause


    【解决方案1】:
    where c.Code == sCode && (string.IsNullOrEmpty(code) || p.Code == code)
    

    这是针对标准 LINQ 的,我不知道它是否适用于 LINQ to SQL。

    编辑: 这适用于short circuit evaluation

    如果c.Code == sCode 为假,则停止评估并返回假
    否则,如果 string.IsNullOrEmpty(code) 为真,则停止评估并返回真
    否则,返回p.Code == code

    【讨论】:

    • 哈哈忍者风格,一定要喜欢“编辑”如何在回答问题 5 分钟左右后才出现。
    • 太棒了!它有效......所以如果 string.IsNullOrEmpty 返回 true 它实际上就像这样 where c.Code == sCode && true - 我假设当 LINQ 在 where 子句中看到 true 时它会忽略它?
    • 这是 linq to sql 吗?如果是这样,最好的方法是运行 sql profiler 跟踪(或使用一种鲜为人知的方法,称为 .ToTraceString()
    【解决方案2】:

    把它放在一个IQueryable&lt;T&gt; 扩展方法中,让它变得非常简单:

    public static IQueryable<Code> WithCodeIfNotEmpty(this IQueryable<Code> source, string code)
    {
       if (string.IsNullOrEmpty(code))
          return source;
       else
          return source.Where(x => x.Code == code);
    }
    

    用法:

    var query = something.WithCodeIfNotEmpty("someCode");
    

    【讨论】:

      【解决方案3】:

      正如其他人所说:

      (string.IsNullOrEmpty(code) || p.Code == code)
      

      顺便说一句,sql可以优化为

         C.Code = isnull(ltrim(rtrim(@code)), c.Code)
      

      【讨论】:

      • 谢谢 Preet .. 这是我面临的问题的非常好的和简单的解决方案。我自己问了一个帖子,人们只是回答了 DLinq 和 ext 方法..我想要的只是你的解决方案..
      【解决方案4】:

      如果您想要 TSQL 给出的直接翻译形式,那么这就是答案

      where
        code == "" ||
        (code != "" &&
        c.Code == code)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-12
        • 1970-01-01
        • 1970-01-01
        • 2016-05-18
        • 1970-01-01
        • 2018-06-20
        • 2015-11-11
        • 2017-08-22
        相关资源
        最近更新 更多