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/