LINQ 列表在 where 子句中给出 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.Contains(p.Nationality)) || (criterias.nationalities == null))
criterias 是一个我存储搜索条件的类。 Nationalities 是一个字符串列表。当我的字符串中没有项目时,就会出现问题。查询抛出空引用异常。该查询不接受国籍中的空值。我该如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
颠倒顺序,以便空检查出现在查询之前:当您使用
||
时,仅当第一部分计算结果为 false 时才计算表达式的第二部分: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:看看这 2 个:
我不认为 weddingDate 会给你带来问题,但生日使用了错误的顺序。
在这种情况下,您需要
||
的“短路评估”属性,将其更改为:Look at these 2:
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:尝试交换国籍检查的顺序。在尝试评估 Contains 之前,它应该在空检查上短路。
Try swapping the order of the nationalties checks. It should short-circuit on the null check before it tries to evaluate the Contains.
翻转此语句:
使其显示为“
如果第一个操作数的计算结果为 true,则将跳过第二个操作数”。
Turn this statement around:
so that it reads
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: