How would one write a LINQ query which takes a hierarchical source data and transforms it so that the grouping is inverted?
Say I have a list of Topic objects each of wh
What you're looking for is a Pivot.
Is it possible to Pivot data using LINQ?
This source contains C# code for a Linq Pivot extension method:
public static class LinqExtensions
{
public static Dictionary> Pivot(this IEnumerable source, Func firstKeySelector, Func secondKeySelector, Func, TValue> aggregate)
{
var retVal = new Dictionary>();
var l = source.ToLookup(firstKeySelector);
foreach (var item in l)
{
var dict = new Dictionary();
retVal.Add(item.Key, dict);
var subdict = item.ToLookup(secondKeySelector);
foreach (var subitem in subdict)
{
dict.Add(subitem.Key, aggregate(subitem));
}
}
return retVal;
}
}