Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

c# - Removing controls in a loop

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 (int i = 0; i < this.Controls.Count; ++i)
{
    if (this.Controls[i].Name.Length == 2)
    {
        this.Controls.Remove(this.Controls[i);
    }
}

But it so happens that the code is wrong. I then change it to:

foreach (Control ctr in this.pbBoardImage.Controls)
{
    if (ctr.Length == 2)
    {
        this.Controls.Remove(ctr);
    }
}

But it still wasn't correct. I know that the correct way would be:

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

However it still doesn't feel elegant. I couldn't use List.RemoveAll, since this.Controls wasn't a List. So can I ask for a more elegant way, preferably without using a loop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...