views:

49

answers:

2

Iam using windows forms. How can I query all child controls of a Form recursively which have a certain type?

In SQL you would use a selfjoin to perform this.

var result = 
  from this 
  join this ????
  where ctrl is TextBox || ctrl is Checkbox
  select ctrl;

Can I also do this in LINQ?

EDIT:

LINQ supports joins. Why can't I use some kind of selfjoin?

A: 

may be this will help you...

http://stackoverflow.com/questions/1558127/how-can-i-get-all-controls-from-a-form-including-controls-in-any-container

once you have the list you can query'em

Luiscencio
+2  A: 

Something like this should work (not perfect code by any means...just meant to get the idea across):

public IEnumerable<Control> GetSelfAndChildrenRecursive(Control parent)
{
    List<Control> controls = new List<Control>();

    foreach(Control child in parent.Controls)
    {
        controls.AddRange(GetSelfAndChildrenRecursive(child));
    }

    controls.Add(parent);

    return controls;
}

var result = GetSelfAndChildren(topLevelControl)
    .Where(c => c is TextBox || c is Checkbox);
Justin Niessner