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.
The correct answer is sorting. Sorting is the process of putting data in a logical order.
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);
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With