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))
标准是我存储搜索标准的类。民族是一个字符串列表。当我在字符串中没有项目时,会出现问题。查询抛出null引用异常。查询不接受国籍中的空值。我怎样才能解决这个问题?
答案 0 :(得分:2)
反转顺序,以便在查询之前进行空检查:当您使用||
时,表达式的第二部分仅在第一部分求值为false时进行评估:
&& ((criterias.nationalities == null) ||
(criterias.nationalities.Contains(p.Nationality)))
答案 1 :(得分:2)
看看这两个:
((criterias.birthday == p.BirthDay|| criterias.birthday == null))
&& ((criterias.marriageDate == null || criterias.marriageDate == p.MarriageDate))
我不认为weddingDate会给你带来问题,但生日会使用错误的订单
在这种情况下,您需要||
的“短路评估”属性,将其更改为:
(criterias.birthday == null || criterias.birthday == p.BirthDay)
&& (criterias.marriageDate == null || criterias.marriageDate == p.MarriageDate)
答案 2 :(得分:1)
尝试交换国税支票的顺序。在尝试评估Contains之前,它应该在空检查上短路。
((criterias.nationalities == null) || (criterias.nationalities.Contains(p.Nationality)))
答案 3 :(得分:1)
转过这句话:
(criterias.nationalities.Contains(p.Nationality)) || (criterias.nationalities == null)
所以它读取
(criterias.nationalities == null) || (criterias.nationalities.Contains(p.Nationality))
如果第一个操作数的计算结果为true,则跳过第二个操作数。
答案 4 :(得分:0)
首先尝试检查null然后(如果它不为null)检查包含:
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))