Collection was modified; enumeration may not execute error when removing a ListItem from a LIstBox

后端 未结 9 619
抹茶落季
抹茶落季 2020-11-29 12:30

I have two ListBoxes, lstAvailableColors and lstSelectedColors. Between each listbox are two buttons, Add and Remove. When a color or colors is selected in lstAvailableCol

相关标签:
9条回答
  • 2020-11-29 12:56

    The problem you face is that you can't modify the collection you itterate thru. You could solve this by using a single linq:

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        lstAvailableColors.Items.RemoveAll(ac => ac.Selected);
    }
    
    0 讨论(0)
  • 2020-11-29 13:03

    It's not possible to modify a collection while you're enumerating it in .Net. You need to separate out your enumeration and remove code into different blocks. Here is a quick sample on how to do that in without LINQ

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        var selected = new List<ListItem>();
        foreach (ListItem item in lstAvailableColors.Items)
        {
            if (item.Selected)
            {
                selected.Add(item);
                lstSelectedColors.Items.Add(item);
            }
        }
        foreach (ListItem item in selected)
        {
            lstAvailableColors.Items.Remove(item);
        }
    }
    

    And here's a more concise version using LINQ

    var selected = lstAvailableColors.Cast<ListItem>().Where(i => i.Selected).ToList();
    selected.ForEach( x => { lstSelectedColors.Items.Add(x); });
    selected.ForEach( x => { lstAvailableColors.Items.Remove(x);});
    

    EDIT

    The LINQ version works in two parts. The first part is the first line which finds the currently selected items and stores the value in a List<ListItem>. It's very important that the line contain the .ToList() call because that forces the query to execute immediately vs. being delayed executed.

    The next two lines iterate through each value which is selected and remove or add it to the appropriate list. Because the selected list is already stored we are no longer enumerating the collection when we modify it.

    0 讨论(0)
  • 2020-11-29 13:03

    This might help you;

    To Remove:

    protected void btnRemove_Click(object sender, EventArgs e)
    {
        {
            for (int i = 0; i < lstAvailableColors.Items.Count; i++)
            { 
                if(lstAvailableColors.Items[i].Selected)
                    lstAvailableColors.Items.RemoveAt(i);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题