删除控件中的所有项目

我目前有一个Sharepoint 2010 Web部件,其中包含多个标签。 我想以编程方式删除除这些标签之外的所有标签。

我尝试了下面的代码,但得到了一个System.InvalidOperationException因为显然在迭代它时不能修改集合。 但是,我不知道怎么试试这个。

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

向后迭代它。

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

你对错误的原因是正确的。 以下使用Linq和ToArray()来解决问题:

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

我会进一步重构这个:

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