Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何删除跳过或传递条件where_C#_Linq - Fatal编程技术网

C# 如何删除跳过或传递条件where

C# 如何删除跳过或传递条件where,c#,linq,C#,Linq,在linq中,我将传入多个变量。在某些情况下,变量将为空。如果var为null,是否有方法有条件地删除每个“where”?例如: var fooQuery = from s in _db.fooTable // var A,B,C,D,E might be null where s.a == varA where s.b == varB where s.c == varC where s.d == varD where s.f == varE

在linq中,我将传入多个变量。在某些情况下,变量将为空。如果var为null,是否有方法有条件地删除每个“where”?例如:

var fooQuery = from s in _db.fooTable
    // var A,B,C,D,E might be null
    where s.a == varA
    where s.b == varB
    where s.c == varC
    where s.d == varD
    where s.f == varE
    select s;
如果其中任何一个变量为空,我想跳过、忽略或跳过“where”

让我更清楚一点

varA和varB为空,因此查询需要进行如下更改:

var fooQuery = from s in _db.fooTable
    //Ignore these 2 where because values are null but keep others

    //ignore where s.a == varA
    //ignore where s.b == varB

    where s.c == varC
    where s.d == varD
    where s.f == varE
    select s; 

只需在条件中包含
null
检查:

where varA == null || s.a == varA

这样做的缺点是空检查现在在数据库服务器上完成。这不是很重要,但值得知道。我认为这是一个优势,因为解析器可以事先确定表达式为false,然后跳过它。这比将所有行连接起来然后检查表达式要好。(不要认为这是不一致的,我同意这是有用的信息)@DavidGWell替代方法是在代码中构建查询,因此
if(varA!=null)fookery==fookery.Where(s=>s.a==varA)啊,是的。这也是一个选择。当然,在这个微不足道的例子中没有太大的好处,但在某些情况下,它可能是一个“陷阱”: