简体   繁体   English

如何按两个值对序列进行分组并保持序列的顺序?

[英]How can I group a sequence by two values and keep the order of the sequence?

Let's say I have a list of Points. 假设我有一个积分列表。

{(0,0), (0,0), (0,1), (0,0), (0,0), (0,0), (2,1), (4,1), (0,1), (0,1)}

How can I group this Points, so that all Points with the same x- and y-value are in one group, till the next element has other values? 如何对这些点进行分组,以便所有具有相同x和y值的点都在一个组中,直到下一个元素具有其他值?

The final sequence should look like this (a group of points is enclosed with brackets): 最终序列应如下所示(一组点用方括号括起来):

{(0,0), (0,0)},
{(0,1)},
{(0,0), (0,0), (0,0)},
{(2,1)},
{(4,1)},
{(0,1), (0,1)}

Note that the order has to be exactly the same. 请注意,顺序必须完全相同。

I believe a GroupAdjacent extension, such as the one listed here (from Eric White's blog) is just what you are looking for. 我相信GroupAdjacent扩展名(例如此处列出的扩展名)(来自Eric White的博客)正是您所需要的。

// Create a no-argument-overload that does this if you prefer...
var groups = myPoints.GroupAdjacent(point => point);

You could write a custom iterator block / extension method - something like this? 您可以编写一个自定义的迭代器块/扩展方法-这样吗?

public static IEnumerable<IEnumerable<Point>> GetGroupedPoints(this IEnumerable<Point> points)
{
    Point? prevPoint = null;
    List<Point> currentGroup = new List<Point>();
    foreach (var point in points)
    {
        if(prevPoint.HasValue && point!=prevPoint)
        {
            //new group
            yield return currentGroup;
            currentGroup = new List<Point>();
        }
        currentGroup.Add(point);
        prevPoint = point;
    }
    if(currentGroup.Count > 0)
        yield return currentGroup;
}
   List<List<Point>> GetGroupedPoints(List<Point> points)
   {
        var lists = new List<List<Point>>();
        Point cur = null;
        List<Point> curList;

        foreach (var p in points)
        {
            if (!p.Equals(cur))
            {
                curList = new List<Point>();
                lists.Add(curList);
            }
            curList.Add(p);
        }

        return lists;
    }
        List<Point> points = new List<Point>(){new Point(0,0), new Point(0,0), new Point(0,1), new Point(0,0), new Point(0,0), new Point(0,0), 
          new Point(2,1), new Point(4,1), new Point(0,1), new Point(0,1)};
        List<List<Point>> pointGroups = new List<List<Point>>();
        List<Point> temp = new List<Point>();
        for (int i = 0; i < points.Count -1; i++)
        {
            if (points[i] == points[i+1])
            {
                temp.Add(points[i]);
            }
            else
            {
                temp.Add(points[i]);
                pointGroups.Add(temp);
                temp = new List<Point>();
            }
        }

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

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