C#: Collection was modified; enumeration operation may not execute

27,394

Solution 1

You are trying to delete a user from the list you are looping trough.

this is impossible. Best is to create a new list and add the good ones in it instead of deleting the bad ones

if (txtEmailID.Text.Length > 0)
    {
        //@new list
        List<EduvisionUser> listOfAcceptedUsers = new List<EduvisionUser>()**

        users = UserRespository.GetUserName(txtEmailID.Text);
        bool isUserAvailable=false;
        foreach (EduvisionUser aUser in users) --->***Exception thrown in this line***
        {
            isUserAvailable = true;

            //Add user to list instead of deleting
            if(aUser.Activated)
            {
                ListOfAcceptedUsers.Add(aUser);
            }
        }

        //check new list instead of old one
        if (ListOfAcceptedUsers.Count == 0 && isUserAvailable)
        {
            DeactivatedUserMessage();
            return;
        }

    }

Solution 2

You can't modify a collection while you're iterating over it with a foreach loop. Typical options:

  • Use a for loop instead
  • Create a separate collection of the items you want to act on, then iterate over that.

Example of the second approach:

List<EduvisionUser> usersToRemove = new List<EduvisionUser>();
foreach (EduvisionUser aUser in users) --->***Exception thrown in this line***
{
    isUserAvailable = true;
    if(!aUser.Activated)
    {
        usersToRemove.Add(aUser);
    }
}
foreach (EduvisionUser userToRemove in usersToRemove)
{
    users.Remove(userToRemove);
}

Another alternative, if you're using List<T> is to use List<T>.RemoveAll:

isUserAvailable = users.Count > 0;
users.RemoveAll(user => !user.Activated);
Share:
27,394
GethuJohn
Author by

GethuJohn

Am a gethu.. u mouth pothu...

Updated on August 01, 2022

Comments

  • GethuJohn
    GethuJohn almost 2 years

    My goal is to delete a user from the user list in my application.But i cannot get to the bottom of this error. Some one plz bail me out.

    if (txtEmailID.Text.Length > 0)
    {
        users = UserRespository.GetUserName(txtEmailID.Text);
        bool isUserAvailable=false;
        foreach (EduvisionUser aUser in users) // Exception thrown in this line
        {
            isUserAvailable = true;
            if(!aUser.Activated)
            {
                users.Remove(aUser);
            }
        }
        if (users.Count == 0 && isUserAvailable)
        {
            DeactivatedUserMessage();
            return;
        }
    }