简体   繁体   English

如果Any()为true,为什么LINQ在Count()上抛出空引用错误?

[英]Why does LINQ throw a null reference error on Count() if Any() is true?

I have a question - why do I get a null reference exception at the .Count() method of this IEnumerable if the .Any() returns true? 我有一个问题-如果.Count() .Any()返回true,为什么我会在此IEnumerable的.Count()方法处获得空引用异常?

 Logger.Normal("{0}", targetWorkflow.GetStages().Any() ? "any is true!" : "any is false");
 Logger.Normal("{0}", targetWorkflow.GetStages().Count());

Error: 错误:

StackTrace = [ at Sth.Workflow.<GetStages>d__13.MoveNext()XX at System.Linq.Enumerable.Count[TSource]

To be honest, I would expect that the Count() method should return at least 1 if .Any() is true, while if Any() was false, it would return 0? 老实说,如果.Any()为true,我希望Count()方法至少返回1,而如果Any()为false,它将返回0?

Let me know where I am wrong, please. 请让我知道我错了。

Also - please note that I am not trying to fix the actual problem, I am trying to understand why Any() == true does not ensure that the collection is healthy and 'countable'. 另外-请注意,我并不是要解决实际问题,而是要了解为什么Any() == true不能确保集合健康且“可数”。

GetStages() appears to be throwing an exception internally within its own code when generating some item that isn't the first item in the sequence. 当生成不是序列中第一项的某些项时, GetStages()似乎在内部在其自己的代码中引发异常。 Any can stop as soon as it gets the first item, which is why it's not throwing any exception, but Count needs to iterate the entire sequence in order to get its result. Any都可以在获得第一个项目后立即停止,这就是为什么它不会引发任何异常,但是Count需要迭代整个序列才能获得其结果。

There is some bug internally in the GetStages() method (or some violation of it's intended usage that you're making) that is unrelated to the code that you've shown. GetStages()方法内部存在一些错误(或与您正在使用的用途有所冲突),这些错误与所显示的代码无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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