If I have a form with this container for example:
+---------------------------------panel 1----+
| |
| +------------------panel 2---+ |
| | | |
| | textbox1 | |
| | combobox1 checkBox1 | |
| +----------------------------+ |
| |
| +------------tableLayoutPanel1-+ |
| | | |
| | textbox2 | |
| +------------------------------+ |
| |
| +-------------FlowLayoutPanel1-+ |
| |textbox3 Combobox2 | |
| +------------------------------+ |
| |
+--------------------------------------------+
I already have a function for getting all controls of a certain type from a given container (with a recursive call to get even controls contained) :
public static IEnumerable<T> FindAllChildrenByType<T>(this Control control)
{
IEnumerable<Control> controls = control.Controls.Cast<Control>();
return controls
.OfType<T>()
.Concat<T>(controls.SelectMany<Control, T>(ctrl => FindAllChildrenByType<T>(ctrl)));
}
This works fine (here it returns textbox1, combobox1, checkbox1, textbox2, textbox3, combobox2)
Now, I want a new function with a similar behavior : get all controls from a container but which are not included in a certain type of container. In my example the function could return all controls contained in panel1 which are never contained in a tableLayoutPanel (here textbox1, combobox1, checkbox1, textbox3, combobox2).
I've tried :
public static IEnumerable<T> FindAllChildrenByType<T>(this Control control)
{
IEnumerable<Control> controls = control.Controls.Cast<Control>();
return controls
.OfType<T>()
.Concat<T>(controls .Where(ctrl => ctrl.GetType() != typeof(TableLayoutPanel))
.SelectMany<Control, T>(ctrl => FindAllChildrenByType<T>(ctrl))
);
}
And :
public static IEnumerable<T> FindAllChildrenByType2<T>(this Control control)
{
IEnumerable<Control> controls = control.Controls.Cast<Control>();
return controls
.OfType<T>()
.Concat<T>(controls.SelectMany<Control, T>(ctrl => FindAllChildrenByType<T>(ctrl)))
.Where<T>(ctrl => ctrl.GetType() != typeof(TableLayoutPanel));
}
with the same result : I get a list of all controls even those which must have been excluded (textBox2 in the TableLayoutPanel in the example).
Any idea of where I got lost?