George Swan's comment is, I think relevant here. A
foreach()
statement is an iterator - it's meant to be a fast way to move forward through an enumeration one element at a time. Once you get out of that particular wheelhouse, it doesn't work well. While it looks like you're working directly on the
List
, odds are that
lines
is, in fact, a hidden
IEnumerable
based on
lines
that the runtime created for the purpose of the
foreach()
construct. It goes out of scope as soon as that loop closes and reverts back to the original collection. The changes you made are lost because they were never in the
List
to begin with.
Where you have your line
foreach(string line in lines)
{
try replacing it verbatim with this:
int listLen = lines.Count;
for( int index = 0; index < listLen; index++ )
{
string line = lines[index];
Leave all of the other lines unchanged. Try it now.
What has changed here is that you've taken control of the iteration manually with the
for()
construct. Now the
lists
collection is left alone. By taking the length of the collection before you begin, you ensure that anything you add to it is not included in the operation. It will only work on the elements that are in the
List
when you begin. However, from your point of view the real benefit here is that now you're actually working directly on the
lines
collection.
C# offers a lot of tools - the trick is to use the right one for the job at hand.