Write a linq expression to select a subtree of elements

Given the class:

class Control
{
    public Control Parent { get; set; }
    public List<Control> Children { get; set; }
}

      

and the list:

List<Control> myControls;

      

Is it possible to write a linq query that will select all children and grandchildren for a given control? For example, if the tree looks like this:

GridA1
  PanelA1
    TextBoxA1
    TextBoxA2
    PanelA2
      ListBoxA1
      ListBoxA2
GridB1
  PanelB1
    TextBoxB1

      

I need a request that, given the myControls list, which contains all of the above controls with parent and child properties set as approriate, can be parameterized by PanelA1 and return TextBoxA1, TextBoxA2, ​​PanelA2, ListBoxA1, and ListBoxA2. Is there an efficient way to do this using linq? I am fetching a tree structure from a database and am looking for a better way to split subtrees than a recursive function.

+1


a source to share


1 answer


This is difficult to do with LINQ, as lambda expressions cannot be self-recursive until they are defined. Recursive function (maybe using LINQ) is the best choice.

How I implement it:



public IEnumerable<Control> ChildrenOf(this IEnumerable<Control> controls)
{
    return controls.SelectMany(c =>
        new Control[] { c }.Concat(ChildrenOf(c.Children)));
}

      

+2


a source







All Articles