Monday, September 9, 2013

Removing List Items while using Foreach Loop

Ever used List.Remove while inside a For Each loop? If so, then you know that it will result to an error since the collection being iterated has changed.

foreach(var item in list)
{
 if(condition)
{
      list.remove(item)    //this will result in error 
}
}


Here's a tip for this case. Attach ".ToList()" .

foreach(var item in list.Tolist())

This way, the list will iterate in a list made by “ToList”. Now you can remove items from the original list without affecting your iteration.

Hope this helps. Happy Coding!

No comments:

Post a Comment