Removing something from a collection
October 11, 2011 Leave a comment
Consider the following snippet:
//Remove all hexes that have a unit in them for (int i = 0; i < returnValue.Count; i++ ) { if (returnValue[i].CurrentUnit != null) { returnValue.RemoveAt(i); } } return returnValue;
This does not work. For example, here is a screen shot:
The reason why is that the indexer is evaluated once,, but the list changes after each iteration. In graphical terms:
0 |
1 |
2 |
3 |
4 |
5 |
X |
|
|
|
X |
|
|
|
|
|
|
|
0 |
1 |
2 |
3 |
4 |
|
|
|
|
X |
|
Index 1 becomes Index 0, and since the loop is already on 1, it gets skipped for evaluation. What we need it to remove a hex and then keep looping – so the while construct needs to be used:
bool keepLooping = true; while (keepLooping == true) { int totalHexes = returnValue.Count; for (int i = 0; i < returnValue.Count; i++) { if (returnValue[i].CurrentUnit != null) returnValue.RemoveAt(i); if (totalHexes == returnValue.Count) keepLooping = false; } }
And the results work as expected: