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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…