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 :-)