Linq To Select DI 包含来自 ControlCollection 的一些文本的所有控件

Linq To Select All controls where DI contains some text from ControlCollection

Linq 一直让我困惑。我正在尝试从 ASP.Net 表单页面中提取所有控件,其中控件的 ID 包含特定字符串。控件集合是分层的,我想 return 所有级别的任何匹配控件。我在球场上的任何地方吗?我真的可以使用一些 help/education。 collection参数是页面中控件的集合,controlID是我要搜索的文本。

    public static Control FindControlsByControlID(ControlCollection collection, string controlID)
    {
        IEnumerable<Control> controls = collection.Cast<Control>();
        IEnumerable<Control> matchedControls = controls
            .SelectMany(p => p.Controls.Cast<Control>()
                .SelectMany(c => c.Controls.Cast<Control>())
                .Where(d => d != null ? d.ID != null ? d.ID.Contains(controlID) : false : false))
            .Where(a => a != null ? a.ID != null ? a.ID.Contains(controlID) : false : false);

        ConcurrentQueue<Control> cq;
        if (matchedControls != null)
            cq = new ConcurrentQueue<Control>(matchedControls);
        else
            return null;
        ...

提前致谢!

使用扩展方法获取所有子控件:

public static class ControlExt {
    public static IEnumerable<Control> AndSubControls(this Control aControl) {
        var work = new Queue<Control>();
        work.Enqueue(aControl);
        while (work.Count > 0) {
            var c = work.Dequeue();
            yield return c;
            foreach (var sc in c.Controls.Cast<Control>()) {
                yield return sc;
                if (sc.Controls.Count > 0)
                    work.Enqueue(sc);
            }
        }
    }
}

现在您可以测试 ControlCollection:

中的所有子控件
IEnumerable<Control> matchedControls = controls.SelectMany(c => c.AndSubControls())
                                               .Where(a => a != null && a.ID != null && a.ID.Contains(controlID));