簡體   English   中英

如何按兩個值對序列進行分組並保持序列的順序?

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

假設我有一個積分列表。

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

如何對這些點進行分組,以便所有具有相同x和y值的點都在一個組中,直到下一個元素具有其他值?

最終序列應如下所示(一組點用方括號括起來):

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

請注意,順序必須完全相同。

我相信GroupAdjacent擴展名(例如此處列出的擴展名)(來自Eric White的博客)正是您所需要的。

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

您可以編寫一個自定義的迭代器塊/擴展方法-這樣嗎?

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