looping(and modifying) a collection

Ok, back to basics with this one.

I have a collection of strings:

1 List<string> someStrings = new List<string>() { "aaaaaaa", "bbb", "ccc", "dddddddd" };

And I want to remove the shorter items (with length < 4), so there should remain two items left.

My first (and amateuristic) attempt was this:

 
1 foreach (string s in someStrings)
2 {
3    if (s.Length < 4)
4       someStrings.Remove(s);
5 }

I always use the foreach loop, but it can’t be used when modifying the collection. (You CAN modify properties of the items in the loop, but not the item reference itself!).
When you do try, you’ll get the “InvalidOperationException: Collection was modified; enumeration operation may not execute.

Somewhere in my gray mass, I reminded to use the for-loop. My second (and dangerous) attempt was this:

 
1 for (int i = 0; i < someStrings.Count; i++)
2 {
3    if (someStrings[i].Length < 4)
4       someStrings.RemoveAt(i);
5 }

No exceptions were thrown, but the outcome is not what you’d expect!! Due to the fact that someStrings.Count and i are out of sync, the item “ccc” is skipped.

So, here’s the correct code:

 
1 for (int i = someStrings.Count - 1; i >= 0; i--)
2 {
3     if(someStrings[i].Length < 4)
4         someStrings.RemoveAt(i);
5 }

Conclusion: use the for-loop and iterate backwards! :p

posted on 2010-09-06 12:48  xqiwei  阅读(180)  评论(0编辑  收藏  举报