James Cadd
James Cadd

Reputation: 12216

Write a linq expression to select a subtree of items

Given a class:

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

and a list:

List<Control> myControls;

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

GridA1
  PanelA1
    TextBoxA1
    TextBoxA2
    PanelA2
      ListBoxA1
      ListBoxA2
GridB1
  PanelB1
    TextBoxB1

I'd like a query that, given list myControls that contains all above controls with Parent and Children properties set as approriate can be parameterized with PanelA1 and return TextBoxA1, TextBoxA2, PanelA2, ListBoxA1 and ListBoxA2. Is there an efficient way to do this with linq? I'm selecting a tree structure out of a database and looking for a better way to pull apart subtrees than a recursive function.

Upvotes: 1

Views: 1004

Answers (1)

mqp
mqp

Reputation: 71937

It's hard to do this in a tremendously pretty way with LINQ, since lambda expressions can't be self-recursive before they're defined. A recursive function (perhaps using LINQ) is your best bet.

How I'd implement it:

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

Upvotes: 2

Related Questions