Recursive control search with LINQ

Take the type/ID checking out of the recursion, so just have a “give me all the controls, recursively” method, e.g.

public static IEnumerable<Control> GetAllControls(this Control parent)
{
    foreach (Control control in parent.Controls)
    {
        yield return control;
        foreach(Control descendant in control.GetAllControls())
        {
            yield return descendant;
        }
    }
}

That’s somewhat inefficient (in terms of creating lots of iterators) but I doubt that you’ll have a very deep tree.

You can then write your original query as:

var checkBoxes = this.GetAllControls()
                     .OfType<CheckBox>()
                     .TakeWhile<CheckBox>(cb => cb.Checked);

(EDIT: Changed AllControls to GetAllControls and use it properly as a method.)

Leave a Comment