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
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 returningnull.I’d check that navData is not
nulland Tables is notnullandTables[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 whenAny()is called. Thus any problems with the query will not manifest until it is actually iterated over.