






















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) |
4 |
someStrings.Remove(s); |
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++) |
3 |
if (someStrings[i].Length < 4) |
4 |
someStrings.RemoveAt(i); |
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--) |
3 |
if(someStrings[i].Length < 4) |
4 |
someStrings.RemoveAt(i); |
Conclusion: use the for-loop and iterate backwards! :p
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。