SkyeBoniwell
SkyeBoniwell

Reputation: 7092

Looping through this collection always misses the last element

I've been trying to fix this loop for a while now. I've gone through a few different generations.

This code loops through a collection of plant objects based on some criteria, and then creates the desired plant object.

It's supposed to use each object in the list.

It's working up until the very last object in the list. For some reason, it just doesn't hit that last member in the collection, it always stops execution before. So I end up with all my needed new plant type objects except the very last one.

This list uses an IList like this:

 IList<PlantType> plants;

Here's the loop:

 var currentPosition = 0;
 var nextPosition = (currentPosition + 1) % plants.Count;
 var stopPosition = plants.Count - 1;   
 var HalfLife = 90;  

 while ((nextPosition != stopPosition) && plants[currentPosition].cell_A + HalfLife >= plants[nextPosition].Cell_Z)
 {
     plantName = plantName + ";" + plants[currentPosition].Name;
     currentPosition = nextPosition;
     nextPosition = (currentPosition + 1) % plants.Count;
 }

 yield return
          CreateNewPlantType(plantName);

I tried changing this part of the while statement:

 (nextPosition != stopPosition) 

to:

 (nextPosition < stopPosition)

but it still misses the last element in the list.

I also tried this:

 (nextPosition <= stopPosition)

but that creates an infinite loop!

So I'm not sure how to go about fixing this.

Any ideas?

Thanks!

Upvotes: 0

Views: 82

Answers (1)

Mogzol
Mogzol

Reputation: 1405

Get rid of the % plants.Count on all your nextPosition definitions. Those are causing the last element to make nextPosition 0.

After that change (nextPosition <= stopPosition) should work.

You could also just change your condition to while ((currentPosition < stopPosition) ..., which in my opinion makes the code a bit easier to read as well.

Upvotes: 2

Related Questions