heyred
heyred

Reputation: 2051

How to loop though a List

Can anyone please help.

I have a problem where I need to loop through 3 lines and check if they are intersecting using C#. The 3 lines will make up the general shape of a triangle. Therefore, only 2 lines will ever be intersecting at a a time.

I have 3 Line objects and I have stored them in List lines. My method to check for intersections currently looks like this:

ProcessIntersections(lines[0], lines[1])
ProcessIntersections(lines[1], lines[2])
ProcessIntersections(lines[2], lines[0])

Looping through the list once I can do, but to check the final intersection, I have to pass in the first line again and check it against the last line.

Is there a better way to process my intersections? How would I be able to loop through the list of lines by only calling ProcessIntersections once? I tried:

for (int i = 0; i < lines.Count; i++)
{
    if (i >= 3)
    {
        i = 0;
        ProcessIntersection(lines[i], lines[i + 1]);
    }
}

But this just lands me in an infinite loop as i keeps on resetting to 0.

Does anyone have any suggestions.

Upvotes: 0

Views: 183

Answers (3)

Serj-Tm
Serj-Tm

Reputation: 16981

Try next loop:

for (int i = 0; i < lines.Count; i++)
{
  var next_i = i + 1;
  if (next_i >= lines.Count)
    next_i = 0;
  ProcessIntersection(lines[i], lines[next_i]);
}

or optimized loop:

for (int i = 0; i < lines.Count; i++)
{
  ProcessIntersection(lines[i], lines[(i + 1) % lines.Count]);
}

Upvotes: 1

ek_ny
ek_ny

Reputation: 10243

for (int i = 0; i < lines.Count; i++)
{
        ProcessIntersection(lines[i], lines[i == lines.Count -1 ? 0 : i + 1]);
}

Upvotes: 1

itsme86
itsme86

Reputation: 19496

If you want to check each line with its successor and then the last line with lines[0], you could do this:

for(int i = 0;i < lines.Count - 1;++i)
    ProcessIntersection(lines[i], lines[i + 1]);
if(lines.Count > 1)
  ProcessIntersection(lines[lines.Count - 1], lines[0]);

If you really want it all handled in the for() loop (which would have a negative impact on speed) you could do this:

for(int i = 0;i < lines.Count;++i)
  ProcessIntersection(lines[i], lines[i == lines.Count - 1 ? 0 : i + 1]);

Upvotes: 1

Related Questions