【问题标题】:Linq To Select All controls where DI contains some text from ControlCollectionLinq 选择所有控件,其中 DI 包含来自 ControlCollection 的一些文本
【发布时间】:2020-07-24 21:43:37
【问题描述】:

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;
        ...

提前致谢!

【问题讨论】:

  • 你所拥有的应该可以工作,但不需要在每个SelectMany 级别进行测试,只需在最后进行测试。另外,请使用&amp;&amp; 而不是?:。但你只会深入两层。
  • FormsNames,而不是IDs?这段代码真的可以编译吗?

标签: linq ienumerable controlcollection


【解决方案1】:

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

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));

【讨论】:

  • 在上面的最后一行中,您使用了 a.Name 而不是 a.ID,但除此之外效果很好。接受这个作为答案。
  • @tjams 对不起,我改了。我使用了Name,因为Systems.Windows.Forms.Control 没有ID 属性...我没有注意到您使用的是Web 表单。
猜你喜欢
  • 2011-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-05
相关资源
最近更新 更多