Grant H.
Grant H.

Reputation: 3717

Linq Object reference not set to an instance of an object - inner collection null

I've got an issue with a linq query that's causing an exception. I know why the exception is happening, but I'm not sure what the best way to rewrite the query is. I'd like to keep it in linq if at all possible, but am not opposed to using loops and null object detection if that's the better approach.

Here's my query - the problem is that AnalysisResults is sometimes null (not simply an empty instantiated collection). That said, it's also possible for the predecessor collections to be null, so I'd prefer an approach that can be applied to all of the collections.

benchmarks = (from p in cacheData.SiteSources
                              from q in p.SiteGroup.SiteGroupSites
                              from r in q.Site.AnalysisResults
                              where r.BufferTypeId == bufferTypeId &&
                              r.BufferValue == bufferValue
                              select r).ToList();

Is there a succinct way to work around the null AnalysisResults?

Upvotes: 1

Views: 731

Answers (2)

smead
smead

Reputation: 1808

You can add some where clauses to check for null

benchmarks = (from p in cacheData.SiteSources
                          where p.SiteGroup.SiteGroupSites != null
                          from q in p.SiteGroup.SiteGroupSites
                          where q.Site.AnalysisResults != null
                          from r in q.Site.AnalysisResults
                          where r.BufferTypeId == bufferTypeId &&
                          r.BufferValue == bufferValue
                          select r).ToList();

Upvotes: 1

ocuenca
ocuenca

Reputation: 39326

Yes, filtering those cases where is null using a Where:

benchmarks = (from p in cacheData.SiteSources
              from q in p.SiteGroup.SiteGroupSites
              where q.Site.AnalysisResults!=null
              from r in q.Site.AnalysisResults
              where r.BufferTypeId == bufferTypeId && r.BufferValue == bufferValue
              select r).ToList();

Upvotes: 2

Related Questions