Create a tree from the list of elements when each element contains a link to the parent

I have a list of type objects Foo. Each object Foocontains a link to the parent:

public class Foo
{
    public Foo Parent { get; set; }
}

(If Parentnull, it Foois considered the "root" of the node.) As you can see, this implies a kind of bottom-up tree hierarchy.

I would like to flip this child> parent relationship in reverse order by wrapping my objects Fooin a new class TreeItem;

public class TreeItem<T>
{
    public T Item { get; set; }
    public IEnumerable<TreeItem<T>> Children { get; set; }
}

As shown, this will give me a more natural top-down tree hierarchy. I believe that this will greatly simplify data binding, for example. in WPF TreeView.

Linq, List<Foo>, Foo TreeItem<Foo>?

Linq, ?

. , " "?

+4
1

ToLookup . .

IEnumerable<Foo> data = GetData();
var lookup = data.ToLookup(foo => foo.Parent);
Func<Foo, TreeItem<object>> selector = null;
selector = foo => new TreeItem<object>()
{
    Item = foo,
    Children = lookup[foo].Select(selector),
};
var rootNodes = lookup[null].Select(selector);

, , , , :

IEnumerable<Foo> data = GetData();
var lookup = data.ToLookup(foo => foo.Parent,
    foo => new TreeItem<object>() { Item = foo });
foreach (var node in lookup.SelectMany(x => x))
    node.Children = lookup[node.Item];
var rootNodes = lookup[null];

, , , . ( , .)

+6

Source: https://habr.com/ru/post/1548532/


All Articles