Linq查询跳过查询空代码
我对Linq查询跳过查询空代码,linq,Linq,我对linq非常陌生。我有我的客户表。我想根据这两个条件选择客户端 客户端类型 客户城市 所以我可以像这样编写查询 from c in clients where c.Type == cType && c.City == cCity 我是否可以使用相同的查询来获得仅提供客户端类型的结果(忽略城市条件。类似于*) 我想做的是,如果cCity或cType为null忽略该条件 这可能吗?这不是你要找的吗 from c in clients where (c.Type == null
linq
非常陌生。我有我的客户表。我想根据这两个条件选择客户端
from c in clients
where c.Type == cType
&& c.City == cCity
我是否可以使用相同的查询来获得仅提供客户端类型的结果(忽略城市条件。类似于*
)
我想做的是,如果cCity或cType为null忽略该条件
这可能吗?这不是你要找的吗
from c in clients
where (c.Type == null || c.Type == cType)
&& (c.City == null || c.City == cCity)
您可以在实际执行LINQ语句之前编写它:
if (cType != null)
clients = clients.Where(c => c.Type == cType);
if (cCity != null)
clients = clients.Where(c => c.City== cCity);
// At this point the query is never executed yet.
如何第一次执行查询的示例:
var results = clients.ToList();
我希望如果
cType==null
跳过查询该条件当c.Type为null时,(c.Type==null | | c.Type==cType)的整个结果为True,因此它被True替换,从而跳过该条件并检查下一个条件链。。因此,您可以解释一下,将true
值硬编码为1==1
有什么好处吗?三元运算的好处是,它返回布尔值,而不是简单的或类似于@Gert answer的条件。1==1始终为真,即如果cType或cCity为空,我们将跳过该条件。我知道1==1
始终为真。为什么不改为写true
:cType==null?true:c.Type==cType
?如果cType为null,则返回true
,否则返回c.Type==cType
。但这就是它的工作原理:cType==null | | c.Type==cType
。所以,问题还在这里。哦,我误解了这个问题。是的,你是对的,我们可以在那里找到真实的。
from c in clients
where (cType == null ? 1 == 1 : c.Type == cType)
&& (cCity == null ? 1 == 1 : c.City == cCity)