【问题标题】:Find all child controls of specific type using Enumerable.OfType<T>() or LINQ使用 Enumerable.OfType<T>() 或 LINQ 查找特定类型的所有子控件
【发布时间】:2011-01-13 16:04:23
【问题描述】:

Existed MyControl1.Controls.OfType&lt;RadioButton&gt;() 仅通过初始集合搜索,不进入子级。

是否可以在不编写自己的递归方法的情况下使用Enumerable.OfType&lt;T&gt;()LINQ 找到所有特定类型的子控件?喜欢this

【问题讨论】:

    标签: c# .net asp.net linq findcontrol


    【解决方案1】:

    我使用扩展方法来展平控件层次结构,然后应用过滤器,所以这是使用自己的递归方法。

    方法是这样的

    public static IEnumerable<Control> FlattenChildren(this Control control)
    {
      var children = control.Controls.Cast<Control>();
      return children.SelectMany(c => FlattenChildren(c)).Concat(children);
    }
    

    【讨论】:

    • 简单、优雅、胜任。 +1。您还可以将所需的子类型指定为通用参数,并使用 OfType() 而不是 Cast,一次性生成列表(避免再次通过所有控件来过滤它们)。
    【解决方案2】:

    我使用这种通用递归方法:

    此方法的假设是,如果控件为 T,则该方法不会查看其子项。如果您还需要查看其子项,您可以轻松地进行相应的更改。

    public static IList<T> GetAllControlsRecusrvive<T>(Control control) where T :Control 
    {
        var rtn = new List<T>();
        foreach (Control item in control.Controls)
        {
            var ctr = item as T;
            if (ctr!=null)
            {
                rtn.Add(ctr);
            }
            else
            {
                rtn.AddRange(GetAllControlsRecusrvive<T>(item));
            }
    
        }
        return rtn;
    }
    

    【讨论】:

      【解决方案3】:

      为了改进上述答案,将返回类型更改为

      //Returns all controls of a certain type in all levels:
      public static IEnumerable<TheControlType> AllControls<TheControlType>( this Control theStartControl ) where TheControlType : Control
      {
         var controlsInThisLevel = theStartControl.Controls.Cast<Control>();
         return controlsInThisLevel.SelectMany( AllControls<TheControlType> ).Concat( controlsInThisLevel.OfType<TheControlType>() );
      }
      
      //(Another way) Returns all controls of a certain type in all levels, integrity derivation:
      public static IEnumerable<TheControlType> AllControlsOfType<TheControlType>( this Control theStartControl ) where TheControlType : Control
      {
         return theStartControl.AllControls().OfType<TheControlType>();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多