假设我有一个积分列表。
{(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)}
请注意,订单必须完全相同。
答案 0 :(得分:4)
我相信一个GroupAdjacent
扩展程序,例如listed here(来自Eric White的博客)正是您正在寻找的。 p>
// Create a no-argument-overload that does this if you prefer...
var groups = myPoints.GroupAdjacent(point => point);
答案 1 :(得分:2)
您可以编写一个自定义迭代器块/扩展方法 - 类似这样的内容吗?
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;
}
答案 2 :(得分:0)
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;
}
答案 3 :(得分:0)
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>();
}
}