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.
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;
}
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>();
}
}
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;
}
精彩评论