【发布时间】:2010-09-08 10:58:07
【问题描述】:
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();
这是个例外:
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 ...
【问题讨论】:
-
确切的例外是什么?您只发布了一个堆栈跟踪...
-
我已经添加了完整的例外。
-
由于 LINQ 的延迟评估,并且查看堆栈跟踪,我猜您的错误出现在创建
dataCollection的代码中。在进行计数之前尝试var x = dataCollection.ToList();- 如果它引发相同的错误,那么问题不在您发布的代码中。 (我假设dataCollection是一个 IEnumerable)。 -
异常的最可能原因是 p.somemoredate 对于某些 p 为空。检查“somedata”是否有 somemoredate == null 的任何项目。
-
对不起,我的意思是
someData.ToList(),而someData是一个 IEnumerable。
标签: c# linq exception-handling linq-to-objects