Home > Enterprise >  How to join elements at IGrouping by key?
How to join elements at IGrouping by key?

Time:09-29

I have IGrouping of Lists of Points like this:

Key 1
List<Point> p1
List<Point> p2

Key 2
List<Point> p3
List<Point> p4

Key 3
List<Point> p5
List<Point> p6

I need to convert this IGrouping to List of IEnumerable by key like this:

var result = new List<IEnumerable<Point>>(){p1.Concat(p2), p3.Concat(p4), p5.Concat(p6)};

How can I did this? Thanks in advice!

CodePudding user response:

Based on the sample input, it looks like you have an IEnumerable<IGrouping<T, List<Point>>>, not IGrouping<T, List<Point>>. The former is what you'd get from IEnumerable<List<Point>>.GroupBy().

In that case, you may use:

var groups = /* TODO: Get the grouped elements */
var result = groups.Select(g => g.SelectMany(x => x)).ToList();

Here, g.SelectMany(x => x) will concatenate the lists that share the same key and groups.Select() will return the concatenated IEnumerable's.

CodePudding user response:

I assume you want the key value to match the position of the elements in the final list. Thus, I'd suggest something like this:

var list = new List<IEnumerable<Point>>();
foreach (var group in groups)
{
    list.Insert(
        index: group.Key, 
        item: group.SelectMany(x => x));
}

This will generate a potentially sparse list where the index of each entry corresponds to the group key, and the value at that position is the IEnumerable of points for that key value.

  • Related