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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With