开发者

C#: Collection was modified; enumeration operation may not execute [duplicate]

This question already has answers here: How to remove elements from a generic list while iterating over it? (28 answers) Closed 9 years ago.

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 (Eduvi开发者_运维问答sionUser aUser in users) // Exception thrown in this line
    {
        isUserAvailable = true;
        if(!aUser.Activated)
        {
            users.Remove(aUser);
        }
    }
    if (users.Count == 0 && isUserAvailable)
    {
        DeactivatedUserMessage();
        return;
    }
}


You can't modify a collection while you're iterating over it with a foreach loop. Typical options:

  • Use a for loop instead
  • Create a separate collection of the items you want to act on, then iterate over that.

Example of the second approach:

List<EduvisionUser> usersToRemove = new List<EduvisionUser>();
foreach (EduvisionUser aUser in users) --->***Exception thrown in this line***
{
    isUserAvailable = true;
    if(!aUser.Activated)
    {
        usersToRemove.Add(aUser);
    }
}
foreach (EduvisionUser userToRemove in usersToRemove)
{
    users.Remove(userToRemove);
}

Another alternative, if you're using List<T> is to use List<T>.RemoveAll:

isUserAvailable = users.Count > 0;
users.RemoveAll(user => !user.Activated);


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

if (txtEmailID.Text.Length > 0)
    {
        //@new list
        List<EduvisionUser> listOfAcceptedUsers = new List<EduvisionUser>()**

        users = UserRespository.GetUserName(txtEmailID.Text);
        bool isUserAvailable=false;
        foreach (EduvisionUser aUser in users) --->***Exception thrown in this line***
        {
            isUserAvailable = true;

            //Add user to list instead of deleting
            if(aUser.Activated)
            {
                ListOfAcceptedUsers.Add(aUser);
            }
        }

        //check new list instead of old one
        if (ListOfAcceptedUsers.Count == 0 && isUserAvailable)
        {
            DeactivatedUserMessage();
            return;
        }

    }


you can do it like this. Use for instead foreach

for( int i =0; i< users.Count; i++ ) --->***Exception thrown in this line***
 {
  EduvisionUser aUser = users[i];
  isUserAvailable = true;
  if(!aUser.Activated)
  {
    users.Remove(aUser);
    i--;
  }
 }


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:

users = users.Where(x => x.Activated);

Or even better, select only what you need from the repository:

users = UserRespository.GetUserName(txtEmailID.Text).Where(x => x.Activated);


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 {

            if (!this.DataWorkspace.ApplicationData.WorkCalendars.CanDelete)
            {
                this.ShowMessageBox("", "", MessageBoxOption.Ok);
                return;
            }

            if (this.WorkCalendars.SelectedItem != null)
            {
                if ((this.WorkCalendars.SelectedItem.FindCalendarWPs.Count() > 0) || (this.WorkCalendars.SelectedItem.FindCalendarWPs1.Count() > 0))
                {
                    Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke
        (() =>
        {
            RadWindow.Alert(" ");
        });
                    return;
                }
                var y = DataWorkspace.ApplicationData.WorkCalendarDays.Where(w => w.WorkCalendar.Id == WorkCalendars.SelectedItem.Id).Execute().AsEnumerable();

                foreach (var item in y)
                {
                    if(item.WorkingHoursCollection != null && item.WorkingHoursCollection.Count() > 0)
                        foreach (var WH in item.WorkingHoursCollection)
                        {
                            WH.Delete();
                        }
                    item.Delete();

                }
                if (this.WorkCalendars.SelectedItem == this.DataWorkspace.ApplicationData.WorkCalendars.Where(U => U.Id == this.WorkCalendars.SelectedItem.Id).SingleOrDefault())
                {
                    Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke
       (() =>
       {
           RadWindow.Alert(" ");
       });
                    return;
                }

                this.WorkCalendars.SelectedItem.Delete();
                this.Save();
            }

        }
        catch (Exception ex)
        {
            Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke
          (() =>
          {
              var msg = new LightSwitchApplication.Presentation.GeneralViews.ExceptionMessage();
              msg.DataContext = ex;
              msg.ShowDialog();
          });
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜