使用 LINQ 进行递归控制搜索 [英] Recursive control search with LINQ

查看:34
本文介绍了使用 LINQ 进行递归控制搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想在 ASP.NET 页面上找到选中的复选框,我可以使用以下 LINQ 查询.

If I wanted to find checked check boxes on an ASP.NET page I could use the following LINQ query.

var checkBoxes = this.Controls
                     .OfType<CheckBox>()
                     .TakeWhile<CheckBox>(cb => cb.Checked);

如果复选框嵌套在当前控件集合中,那效果很好,但我想知道如何通过深入到顶级控件的控件集合来扩展搜索.

That works fine if the checkboxes are nested in the current control collection, but I'd like to know how to extend the search by drilling down into the control collections of the top-level controls.

问题是在这里问的:

在 ASP.NET 中查找使用某个接口的控件

并且收到了非 LINQ 答案,我已经有了我自己版本的递归控件搜索类型和 ID 作为扩展方法,但我只是想知道在 LINQ 中这样做有多容易?

And received non-LINQ answers, I already have my own version of a recursive control search on type and ID as extension methods, but I just wondered how easy this is to do in LINQ?

推荐答案

从递归中取出类型/ID 检查,因此只需使用递归地将所有控件都给我"方法,例如

Take the type/ID checking out of the recursion, so just have a "give me all the controls, recursively" method, e.g.

public static IEnumerable<Control> GetAllControls(this Control parent)
{
    foreach (Control control in parent.Controls)
    {
        yield return control;
        foreach(Control descendant in control.GetAllControls())
        {
            yield return descendant;
        }
    }
}

这有点低效(就创建大量迭代器而言),但我怀疑您是否会拥有非常深的树.

That's somewhat inefficient (in terms of creating lots of iterators) but I doubt that you'll have a very deep tree.

然后您可以将原始查询写为:

You can then write your original query as:

var checkBoxes = this.GetAllControls()
                     .OfType<CheckBox>()
                     .TakeWhile<CheckBox>(cb => cb.Checked);

(将 AllControls 更改为 GetAllControls 并将其正确用作方法.)

( Changed AllControls to GetAllControls and use it properly as a method.)

这篇关于使用 LINQ 进行递归控制搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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