How to avoid nothing with Linq Query?

advertisements

I would like make query with Linq on list of object. In some cases, I ve the following error :

The sequence contains no elements.

My Linq query :

MyList.Where(Function(s) Month(s.Histo_Date) = Month(Date_Reference) - 1 And Year(s.Histo_Date) = Year(Date_Reference)).Average(Function(s) s.Nb_Doc)

After few search I added this : DefaultIfEmpty()

MyList.Where(Function(s) Month(s.Histo_Date) = Month(Date_Reference) - 1 And Year(s.Histo_Date) = Year(Date_Reference)).DefaultIfEmpty().Average(Function(s) s.Nb_Doc)

Now I've the following error :

Object reference not set to an instance of an object

How to avoid Nothing with Linq query ? I like to set the result of Linq query to 0 or String empty if is Nothing.


DefaultIfEmpty has overload which takes "default" value.
Then by adding Select before DefaultIfEmpty you don't need to check for null or create "empty" instance of s

Dim avg = MyList.Where(Function(s) Month(s.Histo_Date) = Month(Date_Reference) - 1 AndAlso Year(s.Histo_Date) = Year(Date_Reference)).
                 Select(Function(s) s.Nb_Doc).
                 DefaultIfEmpty(0).
                 Average()

Not related notice:
Use AndAlso instead of And. And is bitwise operator and always executes both parts of comparison. Where AndAlso will executes only first part if first part fails.

Actually you can remove AndAlso and uses two Where methods - which will be little bid more readable/understandable

Dim monthReference = Month(Date_Reference) - 1
Dim yearReference = Year(Date_Reference)

Dim avg = MyList.Where(Function(s) Month(s.Histo_Date) = monthReference).
                 Where(Function(s) Year(s.Histo_Date) = yearReference).
                 Select(Function(s) s.Nb_Doc).
                 DefaultIfEmpty(0).
                 Average()