I use asp.net 4, ef 4 in c#.
I use System.Web.Security to manage users in my web application.
I have a collection of users in MembershipUserCollection and I need remove some users during a foreach on that collector.
I suppose it is impossible to remove an item from the collector when you are looping.
Do you have any idea how to solve it?
Please provide me a sample of code, thanks!
MembershipUserCollection users = Membership.GetAllUsers();
foreach (MembershipUser x in users)
{
if (!Roles.IsUserInRole(x.UserName, "CMS-AUTHOR"))
{
users.Remove(x.UserName);
}
}
Error:
Collection was modified; enumeration operation may not execute.
You can’t modify an enumeration while traversing it – put the users to remove in a list then remove all of them once you are done enumerating:
or shorter using LINQ: