How to return null in a GroupBy statement when one of the values in the non-key column contains null?

Viewed 281

I want to group a table consisting of 3 columns: Country, Person Name and Grade.

My goal is: when grouping countries that have one or more people with NULL grades, the final output of the GroupBy LINQ statement should be NULL for that specific country, regardless of other people's grades in that country. However, when I write the below code to group it, LINQ assumes that the NULLs are equal to zeros and returns the sum total of the grades for the specific country.

var query = toIEnumerable.GroupBy(c => c.country).Select(r => new
{
    r.Key,
    sumGrade = r.Sum(f => f.grade)
});
1 Answers

You can accomplish this using LINQ's Any method:

var query = toIEnumerable.GroupBy(c => c.country).Select(r =>
{
    bool someWithNoGrades = r.Any(i => i.grade == null);

    return new
    {
        r.Key,
        sumGrade = !someWithNoGrades ? r.Sum(f => f.grade) : null
    };
});
Related