Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

enumeration

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;
    }
}
like image 741
GethuJohn Avatar asked Jul 30 '10 10:07

GethuJohn


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

Why do we write C?

We write C for Carbon Because in some element the symbol of the element is taken form its first words and Co for Cobalt beacause in some elements the symbol of the element is taken from its first second letters, so that the we don't get confuse.


1 Answers

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);
like image 192
Jon Skeet Avatar answered Sep 28 '22 00:09

Jon Skeet