LINQ GroupBy Select only where key is not null

Viewed 409

this may be a simple answer.

I'm making this LINQ expression where I group a list by "Name" and then I create a collection of SymbolFields where the group key (name) is used as name and the values are joined together as the second parameter.

But the question is more, how do I avoid possible null references?

If you look at the picture, you can see that there "might" be scenarios where group.key is null.

I only want to select the ones that are NOT NULL. How can I do so based on my code?

return result
    .GroupBy(r => r.Name)
    .Select(group =>
        new SymbolField(group.Key, string.Join(string.Empty, group.Select(g => g.Symbol))));

enter image description here

1 Answers

I assume this is for Linq-to-Objects (not Linq-to-Entities) and the message you're seeing is a C# 8.0 #nullable warning because r.Name is typed as String? instead of String.

If so, then add a .Where( r => r.Name != null ) step, and then add a ! to the .GroupBy step because this is unfortunately one of the cases that the C# 8.0 compiler's nullability analysis isn't smart enough to detect (yet).

return result
    .Where( r => r.Name != null )
    .GroupBy( r => r.Name! )
    .Select( grp =>
        new SymbolField(
            name     : grp.Key,
            something: string.Join( separator: string.Empty, grp.Select( g => g.Symbol ) )
        )
    );
Related