. Advertisement .
..3..
. Advertisement .
..4..
How to check – collection was modified enumeration operation may not execute? I have the sample detail:
using System; using System.Collections.Generic; namespace DemoApplication { public class Program { static void Main(string[] args) { try { var studentsList = new List<Student> { new Student { Id = 1, Name = "John" }, new Student { Id = 0, Name = "Jack" }, new Student { Id = 2, Name = "Jack" } }; foreach (var student in studentsList) {
if (student.Id <= 0) { studentsList.Remove(student); } else { Console.WriteLine($"Id: {student.Id}, Name: {student.Name}"); } } } catch(Exception ex) { Console.WriteLine($"Exception: {ex.Message}"); Console.ReadLine(); } } } public class Student { public int Id { get; set; } public string Name { get; set; } } }
While I run it, I found the warning message:
Id: 1, Name: John
Exception: Collection was modified; enumeration operation may not execute.
That is my question in my midterm exam, and it is urgent. I searched for the key on some websites, but I didn’t get it. I may miss any line or other changes. I appreciate your assistance!
The cause: The foreach loop is runned on the studentsList. The Id of the student is 0, the item will be removed from the studentsList. Due to this change the studentsList gets modified (resized) and an exception occurs during the runtime.
Solution: Perform a ToList() operation on the studentsList before the start of each iteration.
Output
Unsubscribe a subscriber to change the contents of the Collection of Subscribers during Enumeration.
This can be fixed in a number of ways, including changing the for loop to use an explicitly
.ToList()