Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does LINQ query throw an exception when I attempt to get a count of a type

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                                                    
}; 

Can someone tell me why an exception is thrown when at the following line of code?

int count = dataCollection.Count();  

This is the 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 ...
like image 982
thenth Avatar asked Sep 08 '10 10:09

thenth


People also ask

How does LINQ except work?

LINQ: Except The Except() method requires two collections. It returns a new collection with elements from the first collection which do not exist in the second collection (parameter collection). Except extension method doesn't return the correct result for the collection of complex types.

What is except in LINQ?

In LINQ, the Except method or operator is used to return only the elements from the first collection, which are not present in the second collection. Here is the pictorial representation of the LINQ Except method.

Does LINQ ever return null?

It will return an empty enumerable. It won't be null.

What is skip in LINQ?

In LINQ, the Skip operator is used to skip the specified number of elements from the list/collection and return the remaining elements.


1 Answers

This looks like a normal null reference exception in linq2objects while it tries to execute your predicates or projections.

The cases were you'd get a null ref exception that I can think of are if some elements of the "somedata" collection are null, if "h.Year" is null (what type is that?), or if "p.somemoredate" is null..

like image 195
Diego Veralli Avatar answered Oct 18 '22 21:10

Diego Veralli