Reputation: 335
According to the answer given for the same question: How to check IEnumerable<DataRow> returns null or has any row? and most of the google results I found, you are suppose to use .Any() to verify that the collection contains at least one item.
However, in the following code the .Any() is throwing an "Object reference not set to an instance of an object" exception. Can someone point out what I am doing wrong?
DataSet navData = GetNavigationData();
bool linkFound = false;
if(!CommonLibrary.IsDataSetEmpty(navData))
{
IEnumerable<DataRow> foundLinks = from link in navData.Tables[0].AsEnumerable()
where link.Field<string>("URL").ToLower() == searchURL
select link;
linkFound = (foundLinks.Any());
}
The relevant stack trace showing that the exception is coming from the Any() call:
at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source)
at MyMethod in MySource.cs:line 259
Upvotes: 3
Views: 3497
Reputation: 38397
Your problem is not that Any()
is the problem. Your problem is that a field you are trying to access in your query is most likely returning null
.
I'd check that navData is not null
and Tables is not null
and Tables[0]
is not null. Any() uses deferred execution, so when you assign your query it won't necessarily get processed until it is requested, which happens to be when Any()
is called. Thus any problems with the query will not manifest until it is actually iterated over.
Upvotes: 5