【发布时间】:2011-01-13 16:04:23
【问题描述】:
Existed MyControl1.Controls.OfType<RadioButton>() 仅通过初始集合搜索,不进入子级。
是否可以在不编写自己的递归方法的情况下使用Enumerable.OfType<T>() 或LINQ 找到所有特定类型的子控件?喜欢this。
【问题讨论】:
标签: c# .net asp.net linq findcontrol
Existed MyControl1.Controls.OfType<RadioButton>() 仅通过初始集合搜索,不进入子级。
是否可以在不编写自己的递归方法的情况下使用Enumerable.OfType<T>() 或LINQ 找到所有特定类型的子控件?喜欢this。
【问题讨论】:
标签: c# .net asp.net linq findcontrol
我使用扩展方法来展平控件层次结构,然后应用过滤器,所以这是使用自己的递归方法。
方法是这样的
public static IEnumerable<Control> FlattenChildren(this Control control)
{
var children = control.Controls.Cast<Control>();
return children.SelectMany(c => FlattenChildren(c)).Concat(children);
}
【讨论】:
我使用这种通用递归方法:
此方法的假设是,如果控件为 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;
}
【讨论】:
为了改进上述答案,将返回类型更改为
//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>();
}
【讨论】: