Search code examples
c#linqlambdaforeachcontrolcollection

Foreach over multiple ControlCollections


I have a tab control in my Windows Form, and I want to iterate over each element in two different tabs. When a file is opened, I want all the elements of both to be enabled, and when the file is closed, all to be disabled.

I have no clue how to accomplish this, however, because the controls aren't in an array or list, but in a ControlsCollection. I asked a second ago about foreach statements and learned a bit about lambda, but I don't know how I can apply it here.

Here's what I have:

List<Control.ControlCollection> panels = new List<Control.ControlCollection>();
panels.Add(superTabControlPanel1.Controls);
panels.Add(superTabControlPanel2.Controls);
foreach(Control.ControlCollection ctrlc in panels){
    foreach (Control ctrl in ctrlc) { 

    }
}

Is this possible with one foreach statement, or somehow simpler?


Solution

  • I would use Linq, with the following:

    foreach (var ctrl in panels.SelectMany (x => x.Cast<Control> ())) {
         // Work with the control.
    }
    

    The key is to use the Cast extension method on IEnumerable to make it usable with the SelectMany.