使用LINQ to获得一个网页某种类型的Web控件列表
有使用LINQ获取文本框的列表中的网页,无论它们在树层次结构或容器位置的方法。因此,而不是通过每个容器的ControlCollection循环查找文本框,做同样的事情在LINQ,也许在一个单一的LINQ的语句?
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?
一种方法我见过是创造的ControlCollection扩展方法返回一个IEnumerable ......是这样的:
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);