LINQ SelectMany and Where extension method ignoring nulls
survey.QuestionList
.Where(l => l.Questions != null)
.SelectMany(l => l.Questions)
.Where(q => q != null && q.AnswerRows != null)
.SelectMany(q => q.AnswerRows);
I'd recommend you ensure your collections are never null
. null
can be a bit of a nuisance if you don't handle it well. You end up with if (something != null) {}
all over your code. Then use:
survey.QuestionList
.SelectMany(l => l.Questions)
.SelectMany(q => q.AnswerRows);
A solution that complies with DRY would be to use the null-coalescing operator ??
in your SelectMany
lambda expression.
IEnumerable<IQuestion> questions = survey.QuestionList.SelectMany(q => q.Questions ?? Enumerable.Empty<IQuestion>());
IEnumerable<IAnswerRow> answerRows = questions.SelectMany(q => q.AnswerRows ?? Enumerable.Empty<IAnswerRow>());
In both the OP's code and the above code, questions
and answerRows
will never be null, so the null checks are not required (you may wish to put .Any()
checks depending on your business logic). But the above code will also never result in an exception if q.Questions
or q.AnswerRows
is null.