LINQ List在where子句中给出了null异常

本文关键字:null 异常 List where 子句 LINQ | 更新日期: 2023-09-27 17:59:13

var q = from p in query
where 
   ((criterias.birthday == p.BirthDay|| criterias.birthday == null))                                
&& ((criterias.marriageDate == null || criterias.marriageDate == p.MarriageDate))                                
&& ((criterias.gender == p.Gender) || (criterias.gender == null))
&& ((criterias.nationalities.Contains(p.Nationality)) || (criterias.nationalities == null))

criterias是一个类,我在其中存储搜索标准。国籍是一个字符串列表。当字符串中没有项目时,就会出现问题。查询抛出null引用异常。查询不接受国籍为null的值。我该怎么解决这个问题?

LINQ List在where子句中给出了null异常

反转顺序,使null检查位于查询之前:当您使用||时,只有当第一部分计算为false时,才会计算表达式的第二部分:

&& ((criterias.nationalities == null) || 
             (criterias.nationalities.Contains(p.Nationality)))

看看这2:

   ((criterias.birthday == p.BirthDay|| criterias.birthday == null))
&& ((criterias.marriageDate == null || criterias.marriageDate == p.MarriageDate))  

我不认为结婚日期会给你带来问题,但生日使用了错误的顺序
在这种情况下,您需要||的"短路评估"属性,将其更改为:

   (criterias.birthday == null || criterias.birthday == p.BirthDay)
&& (criterias.marriageDate == null || criterias.marriageDate == p.MarriageDate)

尝试交换nationalities检查的顺序。在尝试评估Contains之前,它应该在null检查时短路。

((criterias.nationalities == null) || (criterias.nationalities.Contains(p.Nationality))) 

扭转这句话:

(criterias.nationalities.Contains(p.Nationality)) || (criterias.nationalities == null)

从而读取

(criterias.nationalities == null) || (criterias.nationalities.Contains(p.Nationality))

如果第一个操作数的计算结果为true,则将跳过第二个操作数。

尝试先检查null,然后(如果不是null(检查contains:

var q = from p in query 
where     
((criterias.birthday == p.BirthDay|| criterias.birthday == null))                                 
&& ((criterias.marriageDate == null ||  criterias.marriageDate == p.MarriageDate))
&& ((criterias.gender == p.Gender) || (criterias.gender == null)) 
&& ((criterias.nationalities == null) || (criterias.nationalities.Contains(p.Nationality))