I created some user controls that I place on a form programmatically in VS 2013. Those controls need to be deleted and recreated on occasion. I have tried deleting the controls two different ways. One works, one doesn't. I'm hoping someone can provide insight as to why the one does not work.
This version does NOT work (it only finds two out of four controls):
// delete user controls from the front panel
foreach (UserControl ctrl in this.Controls.OfType<StationControl>())
{
this.Controls.Remove(ctrl);
}
This version does work (it finds four out of four controls):
// delete user controls from the front panel
var uc_list = this.Controls.OfType<StationControl>().ToArray();
foreach (var ctrl in uc_list)
{
this.Controls.Remove(ctrl);
}
I can count the number of user controls matching the type without issue (e.g.
int controlCount = this.Controls.OfType<StationControl>().Count()
So why does the first foreach statement not fully work?