0

Hi I have an Object named Agency, which contains values for an agency including all of the contacts in a List format. This list would include the contacts details like name, age, address..

I am trying to loop through the list to return only one matching contact from the list, but run into a "Collection was modified; enumeration operation may not execute". When there is 2 contacts left in the list. I am unsure how to handle this, can someone shed a little light, thanks.

            foreach (var x in lstOneContact)
            {
                foreach (var z in x.Contacts)
                {
                    for (int i = 0; i <= x.Contacts.Count; i++)
                    {
                        if (z.ContactId != contactId)
                        {
                            x.Contacts.RemoveAt(i);
                        }
                    }
                }
            }
jpavlov
  • 2,215
  • 9
  • 43
  • 58
  • You are modifying one of the elements you iterate through inside the loop itself: best way known to create an error and/or infinite loop. – varocarbas Nov 21 '13 at 14:29
  • You are iterating `x.Contacts` and at the same time you are trying to remove it inside your nested for loop, You can't modify the collection you are iterating through `foreach` loop. Apart from that your condition in nested `for` loop should be `<` not `<=` since index starts at `0` – Habib Nov 21 '13 at 14:29
  • some value has been modified of list lstOneContact – donstack Nov 21 '13 at 14:29
  • store the contacts to remove in a separate list and after the outer foreach has finished remove the stored contacts from the original list. – mtijn Nov 21 '13 at 14:30
  • you got a class named Agency and in that class you have a list,and you want to remove all contacts from that list that dont have the contactid equal to the variable "contactId",right? – terrybozzio Nov 21 '13 at 14:44

0 Answers0