Monday, 19 October 2015

How to Modified a Collection During in Iteration in C#

When we use Collection in our code , sometime we need to modify (delete) collection
during the Iteration. but we can't remove element directly from collection during the Iteration.
when we  do we got following Exception.

"Cannot Modify a Collection While It Is Being Iterated"


It can solve many ways in this article describe two ways to solve that  

1.Using temporary  List.
2. Can Iterate backward.

Using temporary  List

To describe this method as an example i get source Collection as customerList which the list we want to delete team during iteration. 


var tempList = customerList;      //sourceList
foreach (var item in customerList)
{
    if (item == "Bunny")       // Condition to remove Element
   {
        tempList.Remove(item);
    }
    customerList = tempList;
}



In this way, we didn't modified original collection during the iteration. for that  this method use temp collection for the modification during the iteration and finally assign  that value  to original collection.



Can Iterate backward

To describe this method as an example i get source Collection as customerList which the list we want to delete team during iteration as previous.


for (int i = customerList.Count - 1; i >= 0; i--) {
  if (customerList[i] == something) { // condition to remove element
     customerList.RemoveAt(i);
  }
}





Single Responsibility Principle (SRP)