Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 438
abatishchev Avatar asked Feb 05 '10 19:02

abatishchev


2 Answers

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);
}
like image 128
dh. Avatar answered Sep 22 '22 15:09

dh.


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;
}
like image 1
giammin Avatar answered Sep 24 '22 15:09

giammin