Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq: Create empty IGrouping

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.

like image 546
Brian Berns Avatar asked Dec 28 '22 11:12

Brian Berns


1 Answers

The accepted answer is what I was looking for but it didn't work for me. Maybe I missed something but it didn't compile. I had to modify the code to fix it. Here is the code that worked for me:

public class EmptyGroup<TKey, TValue> : IGrouping<TKey, TValue>
{
    public TKey Key { get; set; }

    public IEnumerator<TValue> GetEnumerator()
    {
        return Enumerable.Empty<TValue>().GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

used like this

var emptyGroup = new EmptyGroup<Customer, AccountingPaymentClient>();
like image 161
ilmatte Avatar answered Mar 05 '23 17:03

ilmatte