问题描述
我在Linq-Where方法中遇到问题.我在where子句中得到了NullReferenceException,这不会发生,因为C#应该使用短路功能,并且第二个操作不能执行:
I have a problem in a Linq-Where method. I get a NullReferenceException in a where clause, which should not happen because C# should use short-circuiting and the second operations hould not be executed:
如果Item
为null,则不应调用Item.State == ...
,因为条件已经为真(短路).
If Item
is null, Item.State == ...
should not be called, because the condition is already true (short-circuiting).
但是,在这种情况下,短路似乎不起作用.
But it seems, that short-circuiting does not working in this case.
其他人有没有解决过这个问题?谢谢!
Does anyone else had and solved this problem? Thank you!
修改:最后,connectionList
不应包含任何空值和断开的连接.
Edit:In the end, the connectionList
should not contains any null-values and no broken connections.
推荐答案
在查询数据库时,这是常见问题.即,将短路行为转换为数据库,不会像您期望的那样工作.您可以阅读有关这种行为的更多信息: (或)使用C#
This is common problem, when querying against databases. Namely, translating short-circuiting behavior against databases, don't work the way as you would expect. You can read more about such behavior: The || (or) Operator in Linq with C#
您可以尝试以下方法:
connectionList.RemoveRange(connectionList.Where(x => x==null));
connectionList.SaveChanges();
connectionList.RemoveRange(connectionList.Where(x => x.Item==BrokenState));
只是看看它是否有效.
这篇关于Linq-Where发生短路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!