I would like to create a function using Linq that summarizes an incoming sequence of values. The function should look something like this:
IDictionary<TKey, Summary<TKey>> Summarize<TKey, TValue>(IEnumerable<TValue> values)
{
return values
.ToLookup(val => GetKey(val)) // group values by key
.Union(*an empty grouping*) // make sure there is a default group
.ToDictionary(
group => group.Key,
group => CreateSummary(group)); // summarize each group
}
The catch is that the resulting IDictionary should have an entry for default(TKey) even if the incoming sequence contains no values with that key. Can this be done in a purely functional way? (Not using mutable data structures.)
The only way I can think to do it is by calling .Union on the lookup before piping it into a dictionary. But that would require me to create an empty IGrouping, which does not appear to be possible without an explicit class. Is there an elegant way to do this?
Edit: We can assume that TKey is a value type.