2011-07-12 40 views
2

我目前有一个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); 
    } 

回答

5

向后迭代它。

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

完美,谢谢 – Landric

1

你是正确的,为什么你得到的错误。以下使用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); 
} 
相关问题