'Collection was modified; enumeration operation may not execute.'

Dung Do Tien Dec 29 2020 34

I have a method to get all active students. I try to use foreach to loop for list of student. But I got System.InvalidOperationException

Here is my code:

public IEnumerable<Student> GetActivatedStudents(List<Student> students)
{
    foreach (var student in students)
    {
        if (!student.IsActivated)
            students.Remove(student);
    }
    return students;
}

 I don't know why I got this exception. Please help me

Have 1 answer(s) found.
  • Actually, You're using foreach to loop for all elements of the list and remove elements while the loop is processing.

    I have 2 solutions for you

    1. Use foreach (var student in students.ToList()) instead of foreach (var student in students)
    2. You can this solution: students.Where(t=>t.IsActivated). I'm using LinQ to get all activte students.

    From my point of view, I prefer the second solution rather than the first one.

     

    Jide Dec 28 2020
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips