除去控制在一个循环 [英] Removing controls in a loop

查看:116
本文介绍了除去控制在一个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我写了一段代码,以消除在满足一定标准形式的所有控件。天真地写吧,这就是我想出

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



但是它仍然没有感到优雅。我不能使用List.RemoveAll,因为this.Controls不是一个列表。所以,我能问一个更优雅的方式,最好不使用循环?

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?

推荐答案

不知道为什么你不喜欢这答案......我突出的重要 RemoveAt移除;然而,在.NET 3.5的替代/ C#3.0:LINQ:

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





(原创)

您不能删除的foreach - 它打破了迭代器。这里的一个普遍的方法是迭代的向后的:

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.

这篇关于除去控制在一个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆