Removing controls in a loop

前端 未结 1 851
无人及你
无人及你 2021-01-05 21:30

Yesterday I wrote a piece of code to remove all the controls in a form that fulfills certain criteria. Writing it naively, this is what I come up with.

for (         


        
相关标签:
1条回答
  • 2021-01-05 21:39

    Not sure why you didn't like this answer... I've highlighted the important RemoveAt; however, as an alternative in .NET 3.5/C# 3.0: LINQ:

            var qry = from Control control in Controls
                      where control.Name.Length == 2
                      select control;
    
            foreach(var control in qry.ToList()) {
                Controls.Remove(control);
            }
    

    (original)

    You can't Remove within foreach - it breaks the iterator. A common approach here is to iterate backwards:

    for (int i = this.Controls.Count - 1; i >= 0; i--) {
        if (this.Controls[i].Name.Length == 2) {
            this.Controls.RemoveAt(i); // <=========== *** RemoveAt
        }
    }
    

    This avoids the "off by one" issues, etc.

    0 讨论(0)
提交回复
热议问题