Is it possible to combine a GroupBy and Select to get a proper named Key?

Viewed 398

I really love the GroupBy LINQ method in C#.

One thing that I don't like though is that the Key is always called Key.

When I loop through the groups, Key doesn't say me anything. So I have to look at the rest of the context to understand what Key actually is.

var grouped_by_competition = all_events
    .GroupBy(e => e.Competition);

foreach ( var group in grouped_by_competition )
{
    [...]
    // ok what is Key for kind of object? I have to look at the outer loop to understand
    group.Key.DoSomething();
}

Of course you could argue it's a small thing, because you only have to look at the outer loop.

In my opinion it still eats 'braincycles' when you're reading it though. So if there are good alternatives that need little boilerplate I would like to use it.

There are some alternatives, but they all add boilerplate code or depend on comments - both I try to omit.

Option 1 - Extra variable inside loop

var grouped_by_competition = all_events
    .GroupBy(e => e.Competition)

foreach ( var group in grouped_by_competition )
{
    var competition = group.Key;
    [...]
    competition.DoSomething();
}

This solution adds unnecessary boilerplate code.

Option 2 - Extra Select

var grouped_by_competition = all_events
    .GroupBy(e => e.Competition)
    .Select(x => new { Competition = x.Key, Items = x } );

foreach ( var group in grouped_by_competition )
{
    [...]
    group.Competition.DoSomething();
}

This solution adds unnecessary boilerplate code.

Option 3 - Add comment close to the use of Key

I rather have expressive code then comments that get outdated.

Summary

Is it theoretically possible to design an extension method that somehow works similar like the anonymous class functionaliy?

var example = new { e.Competition };
example.Competition.DoSomething(); // property name deduced

So we get:

var grouped_by_competition = all_events
    .NamedGroupBy(e => e.Competition);

foreach ( var group in grouped_by_competition )
{
    [...]
    group.Competition.DoSomething();
}
3 Answers
Related