public static
IEnumerable<KeyValuePair<TKey, TOutput>>
GroupAndAggregate<TElement, TKey, TOutput>
(this IEnumerable<TElement> source, Func<TElement, TKey> keyMapping,
Func<TElement, TOutput> firstElementMapping,
Func<TElement, TOutput, TOutput> subsequentElementMapping)
{
Dictionary<TKey, TOutput> dictionary = new Dictionary<TKey, TOutput>();
foreach (TElement element in source)
{
TKey key = keyMapping(element);
TOutput output = default(TOutput);
if (dictionary.TryGetValue(key, out output))
{
output = subsequentElementMapping(element, output);
}
else
{
output = firstElementMapping(element);
}
dictionary[key] = output;
}
return dictionary;
}
IEnumerable<KeyValuePair<TKey, TOutput>>
GroupAndAggregate<TElement, TKey, TOutput>
(this IEnumerable<TElement> source, Func<TElement, TKey> keyMapping,
Func<TElement, TOutput> firstElementMapping,
Func<TElement, TOutput, TOutput> subsequentElementMapping)
{
Dictionary<TKey, TOutput> dictionary = new Dictionary<TKey, TOutput>();
foreach (TElement element in source)
{
TKey key = keyMapping(element);
TOutput output = default(TOutput);
if (dictionary.TryGetValue(key, out output))
{
output = subsequentElementMapping(element, output);
}
else
{
output = firstElementMapping(element);
}
dictionary[key] = output;
}
return dictionary;
}