简体   繁体   中英

LINQ List gives null exception in where Clause

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 isa class where i store my search criterias. nationalities is a string list. the problem occurs when i have no items in string. the query throws null reference exception. the query doesnt accept null value in nationalities. how can i fix this?

Reverse the order so that the null check comes before the query: as you're using || , the second part of the expression is only evaluated when the first part evaluates to false:

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

Look at these 2:

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

I don't think marriageDate will give you problems but birthday uses the wrong order.
In this case you need the 'short-circuit evaluation' property of || , change it to:

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

Try swapping the order of the nationalties checks. It should short-circuit on the null check before it tries to evaluate the Contains.

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

Turn this statement around:

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

so that it reads

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

If the first operand evaluates to true, the second one will be skipped.

Try first check for null then (if it is not null) check for 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM