Is there a way to use linq to get a list of textboxes in a web page regardless of their position in the tree hierarchy or containers. So instead of looping through the ControlCollection of each container to find the textboxes, do the same thing in linq, maybe in a single linq statement?
A:
You're going to need recursion to iterate through all children of all controls. Unless there's some reason you have to implement this with LINQ (I assume you mean lambdas), you might try this approach using Generics instead.
Superstringcheese
2010-08-31 22:21:18
A:
One technique I've seen is to create an extension method on ControlCollection that returns an IEnumerable ... something like this:
public static IEnumerable<Control> FindAll(this ControlCollection collection)
{
foreach (Control item in collection)
{
yield return item;
if (item.HasControls())
{
foreach (var subItem in item.Controls.FindAll())
{
yield return subItem;
}
}
}
}
That handles the recursion. Then you could use it on your page like this:
var textboxes = this.Controls.FindAll().OfType<TextBox>();
which would give you all the textboxes on the page. You could go a step further and build a generic version of your extension method that handles the type filtering. It might look like this:
public static IEnumerable<T> FindAll<T>(this ControlCollection collection) where T: Control
{
return collection.FindAll().OfType<T>();
}
and you could use it like this:
var textboxes = this.Controls.FindAll<TextBox>().Where(t=>t.Visible);
Peter
2010-08-31 22:28:24