C#:集合被修改;枚举操作可能无法执行
我的目标是从应用程序的用户列表中删除用户。但我无法深入了解此错误。请有人保释我。
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;
}
}
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当您使用
foreach
循环迭代集合时,您无法修改集合。典型选项:for
循环第二种方法的示例:
如果您使用
List
,另一种选择是使用列表.RemoveAll
:You can't modify a collection while you're iterating over it with a
foreach
loop. Typical options:for
loop insteadExample of the second approach:
Another alternative, if you're using
List<T>
is to useList<T>.RemoveAll
:您正尝试从循环列表中删除用户。
这是不可能的。最好是创建一个新列表并将好的列表添加到其中,而不是删除坏的列表
You are trying to delete a user from the list you are looping trough.
this is impossible. Best is to create a new list and add the good ones in it instead of deleting the bad ones
你可以这样做。使用 for 代替 foreach
you can do it like this. Use for instead foreach
枚举时不能修改集合。不要删除仅选择您需要的内容,然后让垃圾收集器处理其余的内容:
或者更好的是,从存储库中仅选择您需要的内容:
You cannot modify the collection while enumerating. Instead of removing select only what you need and leave the Garbage Collector take care of the rest:
Or even better, select only what you need from the repository:
我的目标是从 WorkCalendar 中删除 WorkCalendar,但是当选择 WorkHour 的 Wc 时,会抛出如下异常:“集合已修改;枚举操作可能无法执行。”有什么想法吗?感谢您的帮助
删除方法:
尝试
{
My goal is to delete a WorkCalendar from the WorkCalendar but when select Wc that has WorkHour thrown an exception like this:" Collection was modified; enumeration operation may not execute." Any ideas? thanks for the help
Delete method:
try
{