使用Enumerable.OfType ()或LINQ查找特定类型的所有子控件

存在MyControl1.Controls.OfType()仅搜索初始集合,不进入子节点。

是否可以使用Enumerable.OfType()LINQ查找特定类型的所有子控件而无需编写自己的递归方法? 像这样 。

我使用扩展方法来展平控件层次结构,然后应用filter,以便使用自己的递归方法。

该方法看起来像这样

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

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

这种方法的假设是,如果控件是T,则该方法不会查看其子项。 如果你还需要看看它的孩子,你可以很容易地改变它。

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

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

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