c# - 为什么 LINQ 查询会在我尝试获取某种类型的计数时抛出异常

标签 c# linq exception-handling linq-to-objects

public readonly IEnumerable<string> PeriodToSelect = new string[] { "MONTH" };  

var dataCollection = from p in somedata    
from h in p.somemoredate    
where h.Year > (DateTime.Now.Year - 2)    
where PeriodToSelect.Contains(h.TimePeriod)  
select new  
{  
    p.Currency, 
    h.Year.Month, h.Value                                                    
}; 

有人能告诉我为什么在下面的代码行会抛出异常吗?

int count = dataCollection.Count();  

这是异常(exception):

System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Linq.Enumerable.<SelectManyIterator>d__31`3.MoveNext()
   at System.Linq.Enumerable.<SelectManyIterator>d__31`3.MoveNext()
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at ...

最佳答案

这看起来像是 linq2objects 中的正常空引用异常,它试图执行您的谓词或投影。

如果“somedata”集合的某些元素为空,如果“h.Year”为空(那是什么类型?),或者如果“p.somemoredate”为空..

关于c# - 为什么 LINQ 查询会在我尝试获取某种类型的计数时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3666979/

相关文章:

c# - 如何处理由 C++ 加载的 C# DLL 中的异常

c# - 日期选择器未设置阿拉伯文化中的日期

c# - invalidate 方法有什么作用?

c# - "Expression cannot contain lambda expressions"- 异常

c# - ASP.net Linq to SQL同时分组和添加?

linq - EF LINQ 选择 Id 位于列表中的实体

c++ - C++ 中的全局异常处理

php - 如何在 Laravel 5 中处理异常和错误信息?

c# - 测试函数 "System.Web.Mvc.ViewEngines.Engines.FindPartialView"

c# - 为什么关闭嵌套的子对话框也会关闭父对话框?