C#:集合被修改;枚举操作可能无法执行

发布于 2024-09-11 23:41:07 字数 519 浏览 4 评论 0原文

我的目标是从应用程序的用户列表中删除用户。但我无法深入了解此错误。请有人保释我。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

|煩躁 2024-09-18 23:41:07

当您使用 foreach 循环迭代集合时,您无法修改集合。典型选项:

  • 使用 for 循环
  • 创建要操作的项目的单独集合,然后对其进行迭代。

第二种方法的示例:

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);
}

如果您使用 List,另一种选择是使用 列表.RemoveAll

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

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);
↘紸啶 2024-09-18 23:41:07

您正尝试从循环列表中删除用户。

这是不可能的。最好是创建一个新列表并将好的列表添加到其中,而不是删除坏的列表

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 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;
        }

    }
瑾夏年华 2024-09-18 23:41:07

你可以这样做。使用 for 代替 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 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--;
  }
 }
末蓝 2024-09-18 23:41:07

枚举时不能修改集合。不要删除仅选择您需要的内容,然后让垃圾收集器处理其余的内容:

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

或者更好的是,从存储库中仅选择您需要的内容:

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

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);
痴情换悲伤 2024-09-18 23:41:07

我的目标是从 WorkCalendar 中删除 WorkCalendar,但是当选择 WorkHour 的 Wc 时,会抛出如下异常:“集合已修改;枚举操作可能无法执行。”有什么想法吗?感谢您的帮助

删除方法:

尝试
{

            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();
          });
        }

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();
          });
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文