How do I write a LINQ query that inverts the grouping of a hierarchical data source?

后端 未结 3 625
孤独总比滥情好
孤独总比滥情好 2021-02-10 22:57

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

3条回答
  •  伪装坚强ぢ
    2021-02-10 23:32

    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;
        }
    
    }
    

提交回复
热议问题