Linq选择全部控件,其中DI包含ControlCollection中的某些文本

问题描述 投票:0回答:1

Linq总是迷住我。我试图从ASP.Net表单页面中提取所有控件,其中控件的ID包含特定的字符串。控件集合是分层的,我想从所有级别返回所有匹配的控件。我在球场的任何地方吗?我真的可以使用一些帮助/教育。 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;
        ...

提前感谢!

linq ienumerable controlcollection
1个回答
0
投票

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

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.Name != null && a.Name.Contains(controlID));
© www.soinside.com 2019 - 2024. All rights reserved.