Find all child controls of specific type using Enumerable.OfType<T>() or LINQ

橙三吉。 提交于 2019-11-26 11:15:13

问题


Existed MyControl1.Controls.OfType<RadioButton>() searches only thru initial collection and do not enters to children.

Is it possible to find all child controls of specific type using Enumerable.OfType<T>() or LINQ without writing own recursive method? Like this.


回答1:


I use an extension method to flatten control hierarchy and then apply filters, so that's using own recursive method.

The method looks like this

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



回答2:


I use this generic recursive method:

The assumption of this method is that if the control is T than the method does not look in its children. If you need also to look to its children you can easily change it accordingly.

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:


To improve above answer it would make sense to change the return type to

//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>();
}


来源:https://stackoverflow.com/questions/2209854/find-all-child-controls-of-specific-type-using-enumerable-oftypet-or-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!