Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

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.

like image 420
Flagbug Avatar asked Sep 03 '11 15:09

Flagbug


People also ask

Which function is used to arrange the data in a sequence?

The correct answer is sorting. Sorting is the process of putting data in a logical order.


2 Answers

I believe a GroupAdjacent extension, such as the one listed here (from Eric White's blog) is just what you are looking for.

// Create a no-argument-overload that does this if you prefer...
var groups = myPoints.GroupAdjacent(point => point);
like image 136
Ani Avatar answered Feb 02 '23 19:02

Ani


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;
}
like image 43
BrokenGlass Avatar answered Feb 02 '23 20:02

BrokenGlass