代码之家  ›  专栏  ›  技术社区  ›  Martin

仅当不为空时才在where子句中使用变量?一种动态where子句?

  •  6
  • Martin  · 技术社区  · 14 年前

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

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

    在这种情况下,变量(标准c)称为代码。。。如果它不是空的,那么上面的地方是伟大的。。但如果它是空的,我不想把

      where c.Code == sCode
    

    在SQL中,它是这样做的

           AND ( ( @code = '' )
                      OR ( @code <> ''
                           AND C.Code = @code
                         )
    
    4 回复  |  直到 9 年前
        1
  •  10
  •   Greg    14 年前
    where c.Code == sCode && (string.IsNullOrEmpty(code) || p.Code == code)
    

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

    编辑: 这是成功的 short circuit evaluation

    如果 c.Code == sCode 是false,它停止计算并返回false
    否则,如果 string.IsNullOrEmpty(code) 是真的,它停止求值并返回真
    否则,返回 p.Code == code

        2
  •  4
  •   RPM1984    14 年前

    把它放进 IQueryable<T> 使其保持简单的扩展方法:

    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
  •  3
  •   Preet Sangha    14 年前

    如其他人所述:

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

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

       C.Code = isnull(ltrim(rtrim(@code)), c.Code)
    
        4
  •  0
  •   Raymund    14 年前

    如果你想要一个你给出的TSQL的直接翻译表单,那么这就是答案

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