Skip to content

Instantly share code, notes, and snippets.

@jasmin-mistry
Last active January 4, 2016 19:29
Show Gist options
  • Save jasmin-mistry/8667361 to your computer and use it in GitHub Desktop.
Save jasmin-mistry/8667361 to your computer and use it in GitHub Desktop.
public static Dictionary<TFirstKey, Dictionary<TSecondKey, TValue>> Pivot<TSource, TFirstKey, TSecondKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TFirstKey> firstKeySelector, Func<TSource, TSecondKey> secondKeySelector, Func<IEnumerable<TSource>, TValue> aggregate)
{
var retVal = new Dictionary<TFirstKey, Dictionary<TSecondKey, TValue>>();
var l = source.ToLookup(firstKeySelector);
foreach (var item in l)
{
var dict = new Dictionary<TSecondKey, TValue>();
retVal.Add(item.Key, dict);
var subdict = item.ToLookup(secondKeySelector);
foreach (var subitem in subdict)
{
dict.Add(subitem.Key, aggregate(subitem));
}
}
return retVal;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment