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


i have list of points form plane. want create edges between consecutive points , add them list.

here code have:

// points forming plate arraylist points = part.points;  // number of points forming plate int pointcount = points.count;  // create edges list<linesegment> edges = new list<linesegment>(); (int = 0; < pointcount - 1; i++) {     // start , end points     point start = points[i];     point end = points[i+1];      // create edge     linesegment edge = new linesegment(start, end);      // add edge list     edges.add(edge); } 

it doesn't quite work because doesn't create last edge between last , first points on list. way correct it? make work if statement this:

for (int = 0; < pointcount; i++) {     // start , end points     point start = points[i] point;     point end;     if (i == pointcount-1) end = points[0] point;     else end = points[i+1] point;      // rest of code here } 

but i'm sure there more elegant way it. in python start loop -1 first edge connecting last point first point, not possible in c#.

edit: points list given arraylist api.

an 'elegant' solution using modulo:

for (int = 0; < pointcount; i++) {     …     // i+1 == pointcount yield points[0]     point end = points[(i+1) % pointcount] point;     … } 

however, believe if statement used more readable.

note: use list<t> instead of arraylist, too.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -