Removing all but one item from Controls [duplicate

2019-05-18 21:13发布

问题:

This question already has an answer here:

  • How do I loop through items in a list box and then remove those item? 8 answers

I currently have a Sharepoint 2010 web part which includes several labels. I want to programmatically remove all but one of these labels.

I tried the code below but got a System.InvalidOperationException because obviously one can't modify a collection while iterating through it. However, I don't know how else to try this.

    private void clearLabels()
    {
        foreach (Control cont in this.Controls)
            if (cont is Label && cont.ID != "error")
                this.Controls.Remove(cont);
    }

回答1:

Iterate over it backwards.

for(int i = this.Controls.Count - 1; i >= 0; i--)
{
    if (this.Controls[i] is Label && this.Controls[i].ID != "error")
    {
        this.Controls.Remove(this.Controls[i]);
    }
}


回答2:

You are correct as to why you are getting the error. The following using Linq and ToArray() to solve the problem:

private void clearLabels()
    {
        foreach (from cont in this.Controls).ToArray()
            if (cont is Label && cont.ID != "error")
                this.Controls.Remove(cont);
    }

I would refactor this even further to:

private void clearLabels() {

    foreach (from cont in this.Controls 
             where cont is Label && cont.ID != "error"
            ).ToArray()
        this.Controls.Remove(cont);
}