我有问题 - 即使项目没有引用,如何检查 where 子句中的条件?
最基本的方法 - 我正在检查我的类中的字段,该字段可以为空。当我以这种方式检查它时,它将返回空引用异常
var soldOutProducts = from p in list
where p.destinataire.StartsWith("D")
select p;
Run Code Online (Sandbox Code Playgroud)
只需首先检查 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)
| 归档时间: |
|
| 查看次数: |
31141 次 |
| 最近记录: |