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



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

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

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

只需先检查 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"));

当查询变得复杂时,查询表达式非常有用 - 尤其是对于联接和分组。

你能做到

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

最新更新