简体   繁体   English

如何按键加入 IGrouping 中的元素?

[英]How to join elements at IGrouping by key?

I have IGrouping of Lists of Points like this:我有这样的点列表 IGrouping:

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:我需要像这样按键将此 IGrouping 转换为 IEnumerable 列表:

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

How can I do this?我怎样才能做到这一点?

Based on the sample input, it looks like you have an IEnumerable<IGrouping<T, List<Point>>> , not IGrouping<T, List<Point>> .根据示例输入,您似乎有一个IEnumerable<IGrouping<T, List<Point>>> ,而不是IGrouping<T, List<Point>> The former is what you'd get from IEnumerable<List<Point>>.GroupBy() .前者是您从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.在这里, g.SelectMany(x => x)将连接共享相同键的列表,而groups.Select()将返回连接后的IEnumerable

I assume you want the key value to match the position of the elements in the final list.我假设您希望键值与最终列表中元素的 position 相匹配。 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.这将生成一个潜在的稀疏列表,其中每个条目的索引对应于组键,并且 position 处的值是该键值的点的IEnumerable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM