Linq 仅当where子句不为空时才使用变量?一种动态where子句?
是否可以在where(LINQ)中包含子句,但前提是其“NOT”为空 i、 e 在这种情况下,变量(标准c#)称为代码。。。如果它不是空的,那么上面的地方就很好。。但是如果它是空的,那么我不想在其中包含where i、 e 在SQL中,它是这样完成的Linq 仅当where子句不为空时才使用变量?一种动态where子句?,linq,dynamic,where-clause,Linq,Dynamic,Where Clause,是否可以在where(LINQ)中包含子句,但前提是其“NOT”为空 i、 e 在这种情况下,变量(标准c#)称为代码。。。如果它不是空的,那么上面的地方就很好。。但是如果它是空的,那么我不想在其中包含where i、 e 在SQL中,它是这样完成的 AND ( ( @code = '' ) OR ( @code <> '' AND C.Code = @code
AND ( ( @code = '' )
OR ( @code <> ''
AND C.Code = @code
)
和(@code='')
或(@代码“”
C.Code=@Code
)
将其放在IQueryable
扩展方法中,以使其非常简单:
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");
这是针对标准LINQ的,我不知道它是否适用于LINQtoSQL
编辑:
这可以通过
如果c.code==sCode
为false,则停止计算并返回false否则,如果
string.IsNullOrEmpty(code)
为true,它将停止计算并返回true否则,返回其他人所述的
p.code==code
:
(string.IsNullOrEmpty(code) || p.Code == code)
顺便说一句,sql可以优化为
C.Code = isnull(ltrim(rtrim(@code)), c.Code)
如果您想要TSQL提供的直接翻译表单,那么这就是答案
where
code == "" ||
(code != "" &&
c.Code == code)
哈哈,忍者风格,一定很喜欢“编辑”除非在回答问题5分钟左右后才出现。太好了!它可以工作…所以如果string.IsNullOrEmpty返回true,它实际上是这样的,其中c.Code==sCode&&true-我猜当LINQ在where子句中看到true时,它会忽略它?这是LINQ到sql吗?如果是,最好的方法是运行sql探查器跟踪(或者使用一种鲜为人知的方法,名为
.ToTraceString()
)谢谢Preet。这是解决我所面临问题的非常好和简单的方法。我自己问了一篇帖子,人们刚刚回答了DLinq和ext方法。我想要的是你的解决方案。。
(string.IsNullOrEmpty(code) || p.Code == code)
C.Code = isnull(ltrim(rtrim(@code)), c.Code)
where
code == "" ||
(code != "" &&
c.Code == code)