Tutorial :Querying the ASP.NET form object with linq



Question:

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


Solution:1

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.


Solution:2

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>();  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »