Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lỗi "Collection was modified; enumeration operation may not execute" trong C#

Lỗi này xảy ra khi đang loop qua collection (List) và collection bị modify (thêm/xóa data) trong runtime.

Ví dụ gây lỗi

using System;
using System.Collections.Generic;

namespace DemoApplication
{
    public class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var studentsList = new List
                {
                    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); // Modify trong loop
                    }
                    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; }
    }
}

Kết quả

Id: 1, Name: John
Exception: Collection was modified; enumeration operation may not execute.

Foreach loop chạy trên studentsList. Khi Id = 0, item bị Remove từ studentsList. Collection bị modified (resized) nên exception ném ra runtime.

Fix

Thực hiện ToList() trên studentsList trước khi bắt đầu iteration.

foreach (var student in studentsList.ToList())

Ví dụ đã fix

using System;
using System.Collections.Generic;
using System.Linq;

namespace DemoApplication
{
    public class Program
    {
        static void Main(string[] args)
        {
            var studentsList = new List
            {
                new Student { Id = 1, Name = "John" },
                new Student { Id = 0, Name = "Jack" },
                new Student { Id = 2, Name = "Jack" }
            };

            foreach (var student in studentsList.ToList())
            {
                if (student.Id <= 0)
                {
                    studentsList.Remove(student);
                }
                else
                {
                    Console.WriteLine($"Id: {student.Id}, Name: {student.Name}");
                }
            }
            Console.ReadLine();
        }
    }

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Kết quả

Id: 1, Name: John
Id: 2, Name: Jack