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
Linq查询跳过查询空代码_Linq - Fatal编程技术网

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)