asa
asa

Reputation: 779

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

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)
});

Upvotes: 2

Views: 592

Answers (1)

Tobias Tengler
Tobias Tengler

Reputation: 7454

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
    };
});

Upvotes: 2

Related Questions