0

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

提前致谢!

4

1 回答 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.ID != null && a.ID.Contains(controlID));
于 2020-04-13T20:52:59.437 回答