I am looking for some input with this error. I am clear about a few things but not sure how to fix this linq expression. This error happens for our users and I can't reproduce this problem. So I tried to find where we use distinct operator with selectmany and found one occurrence in the routine.
var finishedReqs = allDocs.SelectMany(x => x.Reqs).Distinct().ToList();
var finishedReqsWithDocs = finishedReqs.Where(x => x.Docs.Any());
if (finishedReqsWithDocs.Any())
{
//Call another routine
}
Exception
-----------------
Message:
Object reference not set to an instance of an object.
Stack Trace:
at System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()
at System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()
at System.Linq.Enumerable.<DistinctIterator>d__81`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
I understand that if the collection is null, SelectMany returns null instead of an empty list. And then I am confused because we do a Distinct.ToList(). Where do I need to check for nulls. Resharper tells me the first expression with Distinct.ToList() can never be null
if(finishedReqs!=null) //Resharper has squiggly lines with expression is always true
{
}