用什么集合来存储树结构? [英] What collection to store a tree structure?
问题描述
我想在集合中存储组织结构图.我认为树数据结构最适合我的需求,因为我需要向一个节点添加多个节点.
I want to store an organisation chart in a collection. I think a tree data structure will be best suited to my needs, as I need to add multiple nodes to one node.
LinkedList
仅提供将一个节点添加到另一个节点的功能,如果我理解正确的话.
LinkedList
only provides adding one node to another node, if I understand it correctly.
我看过 C5 treeset
集合,但它似乎没有 Add()
方法可以将 2 个以上的节点添加到一个节点.
I have looked at C5 treeset
collection, but it doesn't seem to have Add()
method to add more than 2 nodes to one node.
我还查看了 Windows 窗体库中的 Treeview
类,但我不想将 Windows 窗体 dll 添加到我的项目中,因为我正在构建一个服务层应用.(或者还好吗?)
I have also looked at Treeview
class from Windows Forms library, but I do not want to add Windows forms dll to my project, since I am building a service layer application. (or is it fine?)
我不想写自己的树集合类,如果第三方已经提供了一个?
I do not want to write my own tree collection class, if there is already one provided by 3rd party?
有什么建议吗?
谢谢
推荐答案
这样的事情可以作为一个起点.通过使用泛型,这个人可以拥有一棵任何东西的树
Something like this can be a starting point. By using generics this one can hold a tree of anything
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;
}
}
一个包含字符串树的样本
A sample which holds a tree of strings
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");
这篇关于用什么集合来存储树结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!