Linq - 检查where子句中的条件如果字段可以为空

bos*_*ski 1 c# linq

我有问题 - 即使项目没有引用,如何检查 where 子句中的条件?

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

 var soldOutProducts = from p in list 
            where p.destinataire.StartsWith("D") 
            select p; 
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

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

where p.destinataire != null && p.destinataire.StartsWith("D")
Run Code Online (Sandbox Code Playgroud)

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

where p != null && p.destinataire != null && p.destinataire.StartsWith("D")
Run Code Online (Sandbox Code Playgroud)

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

var soldOutProducts = list.Where(p => p.destinataire != null && 
                                      p.destinataire.StartsWith("D"));
Run Code Online (Sandbox Code Playgroud)

当查询变得复杂时,查询表达式确实非常有用 - 特别是在连接和分组方面。


小智 5

你可以做

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

  • 为什么要费心使用“IsNullOrEmpty”而不是简单的“null”测试?空字符串不以“D”开头,因此它应该给出相同的结果,并且这是一种更通用的方法,适用于所有可为空的类型,而不仅仅是字符串。 (2认同)