JayByte JayByte - 4 months ago 9
C# Question

How to iterate through a list so that the last iteration step goes back to the first object?

I have a list of points that form a plane. I want to create edges between consecutive points and add them to another list.

Here is the code I currently have:

// Get points forming the plate
ArrayList points = part.points;

// Number of points forming the plate
int pointCount = points.Count;

// Create edges
List<LineSegment> edges = new List<LineSegment>();
for (int i = 0; i < pointCount - 1; i++)
{
// Get start and end points
Point start = points[i];
Point end = points[i+1];

// Create edge
LineSegment edge = new LineSegment(start, end);

// Add edge to the list
edges.Add(edge);
}


It doesn't quite work because it doesn't create the last edge between the last and the first points on the list. What would be the way to correct it? I could make it work with an if statement like this:

for (int i = 0; i < pointCount; i++)
{
// Get start and end points
Point start = points[i] as Point;
Point end;
if (i == pointCount-1) end = points[0] as Point;
else end = points[i+1] as Point;

// Rest of the code here
}


But I'm sure there is a more elegant way to do it. In Python I would start the loop from -1 so that the first edge would actually be connecting the last point to the first point, but that is not possible in C#.

EDIT: The points list is given as an ArrayList by the API.

Answer

An 'elegant' solution is using a modulo:

for (int i = 0; i < pointCount; i++)
{
    …
    // for i+1 == pointCount this will yield points[0]
    Point end = points[(i+1) % pointCount] as Point;
    …
}

However, I believe the if statement you used is more readable.

Note: Use a List<T> instead of ArrayList, too.