I have a list of objects of type Foo
. Each Foo
object contains a reference to its parent:
public class Foo
{
public Foo Parent { get; set; }
}
(If Parent
is null, then the Foo
is considered to be a 'root' node.) As you can see, this implies a sort of "bottom-up" tree hierarchy.
I would like to flip this child->parent association upside-down by wrapping my Foo
objects in a new class called TreeItem
;
public class TreeItem<T>
{
public T Item { get; set; }
public IEnumerable<TreeItem<T>> Children { get; set; }
}
As illustrated, this would give me a more natural "top-down" tree hierarchy. I believe this would allow for much easier data binding, eg. in a WPF TreeView
.
Is there a concise Linq statement which would be able to take a List<Foo>
, find each Foo
object's children, and spit out the correspondingly-converted list of TreeItem<Foo>
?
Barring a Linq query, what would be the simplest algorithm?
Bonus: What words or search terms would you use, to describe this "tree-flipping" transformation?