tags:

views:

125

answers:

2

Is it possible to select all controls that inherit a particular abstract class with linq.

+2  A: 

Make use of the Enumerable.OfType<T> extension method:

...Form.Controls.OfType<MyControlBase>()...

To perform this recursively see the other answer: create an iterator that walks the control tree to create a list which you then apply LINQ operators to.

Richard
I guess the controls I'm looking for are nested in another. When I try this it returns nothing.
Slim
Yes you'd have to recursively descend through the controls collection gathering them up as you go.
Winston Smith
So why use linq if you have to iterate with loops?
Slim
@Slim: Because it gives you some seriously powerful filtering and processing capabilities, once one reusable loop is written.
Richard
+2  A: 

Assuming you have a method which recursively gets all the controls, as follows:

public static IEnumerable<Control> GetControls(Control form) {
    foreach (Control childControl in form.Controls) {   // Recurse child controls.
        foreach (Control grandChild in GetControls(childControl)) {
            yield return grandChild;
        }
        yield return childControl;
    }
}

Then you can do:

var controls = GetControls(form).OfType<SomeControlBase>();
Winston Smith