使用LINQ to获得一个网页某种类型的Web控件列表 [英] Using linq to get list of web controls of certain type in a web page

查看:152
本文介绍了使用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);

这篇关于使用LINQ to获得一个网页某种类型的Web控件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆