【问题标题】:Linq - check condition in where clause if field can be nullLinq - 如果字段可以为空,则检查 where 子句中的条件
【发布时间】:2014-02-10 09:50:42
【问题描述】:

我有一个问题 - 即使项目没有参考,如何检查 where 子句中的条件?

最基本的方法 - 我正在检查我的班级中的字段,该字段可以为空。当我以这种方式检查它时,它将返回空引用异常

 var soldOutProducts = from p in list 
            where p.destinataire.StartsWith("D") 
            select p; 

【问题讨论】:

标签: c# linq


【解决方案1】:

你可以吗

var soldOutProducts = from p in list
                      where !string.IsNullOrEmpty(p.destinataire) and
                            p.destinataire.StartsWith("D")
                      select p;

【讨论】:

  • 为什么要麻烦使用IsNullOrEmpty 而不是简单的null 测试?空字符串不以D 开头,因此它应该给出相同的结果,并且它是一种更通用的方法,适用于所有可为空的类型,而不仅仅是字符串。
  • @JonSkeet 可能是一种习惯的力量。或者严格的代码分析规则,我认为默认的 VS CA 设置告诉你使用string.IsNullOrEmpty 而不是s == null :D
【解决方案2】:

首先检查 null,就像在循环中编写普通 C# 代码一样。

where p.destinataire != null && p.destinataire.StartsWith("D")

如果p 本身可以为空(即您的列表可以包含空元素),那么您也需要检查:

where p != null && p.destinataire != null && p.destinataire.StartsWith("D")

请注意,如果您的查询表达式只是进行过滤,您可能希望使用点表示法:

var soldOutProducts = list.Where(p => p.destinataire != null && 
                                      p.destinataire.StartsWith("D"));

当查询变得复杂时,查询表达式非常有用——尤其是在连接和分组方面。

【讨论】:

    【解决方案3】:
     var soldOutProducts = from p in list 
                where p.destinataire != null && p.destinataire.StartsWith("D") 
                select p; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 2018-12-23
      • 2016-11-27
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多