开发者

Use variable in where clause only if NOT empty? A kind of dynamic where clause?

Is it possible to include a clause in the where (LINQ) but only if its "NOT" empty ?

i.e.

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

In this case the variable (standard c#) is called code ... if its NOT empty then the above where is great.. but if its empty then i don't want to include in it the where

i.e.

开发者_运维技巧  where c.Code == sCode

In SQL its done like this

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


where c.Code == sCode && (string.IsNullOrEmpty(code) || p.Code == code)

That's for standard LINQ, I have no idea if it works for LINQ to SQL.

Edit: This works through short circuit evaluation

if c.Code == sCode is false, it stops evaluating and returns false
otherwise, if string.IsNullOrEmpty(code) is true, it stops evaluating and returns true
otherwise, return p.Code == code


Put that in an IQueryable<T> extension method to keep it really simple:

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);
}

Usage:

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


As stated by others :

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

btw sql can be optimised to

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


If you want a direct translation form that TSQL you given then this is the answer

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜