Tuesday, May 26, 2015

remove item in foreach loop c#

You will face error if u directly remove the item during the for each loop because dynamic changes on the loop parent is not allow. info msdn forum

here is what you should do:
Assign the object list into another (new) list, while looping, make changes to the original object.
eg:
List<Customer> custList = Customer.Populate();
      foreach (var cust in custList.ToList())
      {
        Customer.Remove(cust);
      }

No comments:

Post a Comment