存储树结构的集合是什么?

gun*_*erz 11 c# collections tree

我想在组合中存储组织结构图.我认为树数据结构最适合我的需要,因为我需要向一个节点添加多个节点.

LinkedList 如果我理解正确的话,只提供一个节点添加到另一个节点.

我看过C5 treeset集合,但它似乎没有Add()方法向一个节点添加2个以上的节点.

我也Treeview从Windows窗体库查看了类,但我不想将Windows窗体dll添加到我的项目中,因为我正在构建服务层应用程序.(或者没事?)

我不想写自己的树集合类,如果已经有第三方提供的那个?

有什么建议吗?

谢谢

cel*_*lik 26

这样的事情可以作为一个起点.通过使用泛型,这个可以容纳任何树

class TreeNode<T>
{
    List<TreeNode<T>> Children = new List<TreeNode<T>>();

    T Item {get;set;}

    public TreeNode (T item)
    {
        Item = item;
    }

    public TreeNode<T> AddChild(T item)
    {
        TreeNode<T> nodeItem = new TreeNode<T>(item);
        Children.Add(nodeItem);
        return nodeItem;
    }
}
Run Code Online (Sandbox Code Playgroud)

一个持有一串字符串的样本

string root = "root";
TreeNode<string> myTreeRoot = new TreeNode<string>(root);
var first = myTreeRoot.AddChild("first child");
var second = myTreeRoot.AddChild("second child");
var grandChild = first.AddChild("first child's child");
Run Code Online (Sandbox Code Playgroud)