Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to aggregate a dictionary using LINQ?

I am trying to build a dictionary from an enumerable, but I need an aggregator for all potentially duplicate keys. Using ToDictionary() directly was occasionally causing duplicate keys.

In this case, I have a bunch of time entries ({ DateTime Date, double Hours }), and if multiple time entries occur on the same day, I want the total time for that day. I.e., a custom aggregator, that will give me a unique key for a dictionary entry.

Is there a better way to do it than this?

(This does work.)

    private static Dictionary<DateTime, double> CreateAggregatedDictionaryByDate( IEnumerable<TimeEntry> timeEntries )
    {
        return
            timeEntries
                .GroupBy(te => new {te.Date})
                .Select(group => new {group.Key.Date, Hours = group.Select(te => te.Hours).Sum()})
                .ToDictionary(te => te.Date, te => te.Hours);
    }

I think I'm really looking for something like this:

IEnumerable<T>.ToDictionary( 
    /* key selector : T -> TKey */, 
    /* value selector : T -> TValue */, 
    /* duplicate resolver : IEnumerable<TValue> -> TValue */ );

so...

timeEntries.ToDictionary( 
    te => te.Date, 
    te => te.Hours, 
    duplicates => duplicates.Sum() );

The 'resolver' could be .First() or .Max() or whatever.

Or something similar.


I had one implementation... and another one showed up in the answers while I was working on it.

Mine:

    public static Dictionary<TKey, TValue> ToDictionary<T, TKey, TValue>(
        this IEnumerable<T> input, 
        Func<T, TKey> keySelector, 
        Func<T, TValue> valueSelector, 
        Func<IEnumerable<TValue>, TValue> duplicateResolver)
    {
        return input
            .GroupBy(keySelector)
            .Select(group => new { group.Key, Value = duplicateResolver(group.Select(valueSelector)) })
            .ToDictionary(k => k.Key, k => k.Value);
    }

I was hoping there was something like that already, but I guess not. That would be a nice addition.

Thanks everyone :-)

like image 517
Jonathan Mitchem Avatar asked Jul 26 '10 19:07

Jonathan Mitchem


1 Answers

public static Dictionary<KeyType, ValueType> ToDictionary
  <SourceType, KeyType, ValueType>
(
  this IEnumerable<SourceType> source,
  Func<SourceType, KeyType> KeySelector,
  Func<SourceType, ValueType> ValueSelector,
  Func<IGrouping<KeyType, ValueType>, ValueType> GroupHandler
)
{
  Dictionary<KeyType, ValueType> result = source
    .GroupBy(KeySelector, ValueSelector)
    .ToDictionary(g => g.Key, GroupHandler);
}

Called by:

Dictionary<DateTime, double> result = timeEntries.ToDictionary(
  te => te.Date,
  te => te.Hours,
  g => g.Sum()
);
like image 117
Amy B Avatar answered Sep 28 '22 03:09

Amy B