I have to delete some rows from a data table. I've heard that it is not ok to change a collection while iterating through it. So instead of a for loop in which I check if a row meets the demands for deletion and then mark it as deleted, I should first iterate through the data table and add all of the rows in a list, then iterate through the list and mark the rows for deletions. What are the reasons for this, and what alternatives do I have (instead of using the rows list I mean)?.
C# – How to modify or delete items from an enumerable collection while iterating through it in C#
ccollectionsiteration
Related Topic
- Javascript – How to skip to next iteration in jQuery.each() util
- Python – How to remove items from a list while iterating
- C# – How to remove elements from a generic list while iterating over it
- C# – Intelligent way of removing items from a List
while enumerating in C# - Java – Remove elements from collection while iterating
- Java – Ways to iterate over a list in Java
- Scala: list.flatten: no implicit argument matching parameter type (Any) = > Iterable[Any] was found
Best Answer
Iterating Backwards through the List sounds like a better approach, because if you remove an element and other elements "fall into the gap", that does not matter because you have already looked at those. Also, you do not have to worry about your counter variable becoming larger than the .Count.