listmergeigrouping

How to merge two Lists of IGrouping?


Given I have two lists of type IGrouping:

List<IGrouping<long, string>>:
a) Key: 1 Values: "a", "b", "c"
        2         "d", "e"
b)      1         "aa", "bb", "cc"
        3         "f", "g"

And I would like to merge both to one:

Key: 1 Values: "a", "b", "c", "aa", "bb", "cc"
     2         "d", "e"
     3         "f", "g"

Can anyone help? Thank you.


Solution

  • I got it working, not the best solution though.

        public static IList<IGrouping<T, TU>> MergeGroupingList<T, TU>( IList<IGrouping<T, TU>> groupings )
        {
            IEnumerable<KeyValuePair<T, TU>> temp = ( from grouping in groupings
                                                      from value in grouping
                                                      select new KeyValuePair<T, TU>( grouping.Key, value ) ).ToList();
            return temp.GroupBy( r => r.Key, r => r.Value ).ToList();
        }