递归控制搜索与LINQ递归、LINQ

2023-09-08 08:43:22 作者:请吃饭的关系

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

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.

有人问在这里:

Finding使用某个接口的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.)