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
2009-05-05 20:08:08
I guess the controls I'm looking for are nested in another. When I try this it returns nothing.
Slim
2009-05-06 03:36:42
Yes you'd have to recursively descend through the controls collection gathering them up as you go.
Winston Smith
2009-05-06 08:41:11
So why use linq if you have to iterate with loops?
Slim
2009-05-07 19:27:36
@Slim: Because it gives you some seriously powerful filtering and processing capabilities, once one reusable loop is written.
Richard
2009-05-07 20:20:31
+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
2009-05-06 08:45:33