为什么错误集合被修改;枚举操作可能不会执行,如何在C#中处理它?
当在集合(例如:列表)上运行循环过程并且在运行时修改集合(添加或删除数据)时,会发生此错误。
示例
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; }
}
}输出结果
上面代码的输出是
Id: 1, Name: John Exception: Collection was modified; enumeration operation may not execute.
在上面的示例中,foreach循环在studentsList上执行。当学生的ID为0时,该项目将从studentsList中删除。由于此更改,studentsList会被修改(调整大小),并且在运行时会引发异常。
解决以上问题
为了克服上述问题,请ToList()在每次迭代开始之前对studentsList进行操作。
foreach (var student in studentsList.ToList())
示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
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.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; }
}
}上面代码的输出是
输出结果
Id: 1, Name: John Id: 2, Name: Jack