Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DefaultIfEmpty in Linq - problem substituting a null value for a default value

Tags:

c#

linq

I have questions that may or may not have a question_group

if all the questions do not have a question_group and if I use default if empty like this:

question_group defaultQuestion = new question_group {question_group_id = Guid.Empty};
questions.Select(x => x.question_group).DefaultIfEmpty(defaultQuestion).Distinct();

shouldn't I get an IEnumerable<question_group> containing only the default question_group that I defined? I get null.... what am I missing here?

like image 802
FiveTools Avatar asked May 21 '10 17:05

FiveTools


1 Answers

I think DefaultIfEmpty works differently from how you expect. If your question has no question group, presumably this means its question group is null. DefaultIfEmpty only has an effect on empty enumerables (that is, the number of elements is zero). An enumerable containing some nulls is not empty.

I think what you probably want to do is to remove all the question groups that are null and then check to see if the enumerable is empty. You might want to try something like this instead:

var questionGroups = questions.Select(x => x.question_group)
                              .Where(x => x != null)
                              .DefaultIfEmpty(defaultQuestion)
                              .Distinct();
like image 63
Mark Byers Avatar answered Sep 17 '22 07:09

Mark Byers