我有一个从数据库管理器类获得的数据表, 我需要将该数据转换为层次结构
直接将其绑定(bind)到 .net TreeView 控件或首先绑定(bind)到内存中。
我有一个 ID 列和一个 ParentID 列。 我不知道的一定是 parent ID。所以首先要做的就是找出哪个节点是父 ID。
循环此表并使其分层的最佳实践是什么
BranchId ParentId ProductCount HasBranchChildren Name
0 NULL 48 1 Categories
1 0 20 1 CategoryA
2 1 10 1 CategoryA1
3 1 8 0 CategoryA2
4 1 2 0 CategoryA3
5 2 4 0 CategoryA1.1
6 2 6 0 CategoryA1.2
7 0 28 1 CategoryB
8 7 20 0 CategoryB1
9 7 8 0 CategoryB2
这将是一个示例数据表 当然它会有数百个项目,并且并不总是从根节点开始, 一个请求可能会请求某个类别的子集, 但是我已经与数据库团队交谈过,他们会给我根节点上的 NULL 在上面的例子中,这将是表中的元素 0 ....
最佳答案
根节点的 ParentId 属性将/必须为 null 或 0 或某个告诉您它们没有父节点的值。然后您可以开始递归搜索以当前节点 id 作为父节点的节点。如果您只想在树中显示集合,则无需将其以分层结构保存在内存中,您可以继续构建树。像这样的事情:
// just a concept, not tested, might have errors
// ObjectWithHierarchy could look something like this
class ObjectWithHierarchy
{
public int Id {get;set;}
public int? ParentId {get;set;}
public string Name {get;set;}
}
private void LoadTree()
{
// initialize your collection of objects
List<ObjectWithHierarchy> list = new List<ObjectWithHierarchy>();
// build the tree
TreeView treeView = new TreeView();
foreach (var item in list.FindAll(i => i.ParentId == null))
{
// create the root node
TreeNode rootNode = new TreeNode();
rootNode.Text = item.Name;
rootNode.Tag = item;
// load child nodes
LoadChildNodes(node, list);
// add the node to the treeview
treeView.Nodes.Add(rootNode);
}
}
private void LoadChildNodes(TreeNode node, List<ObjectWithHierarchy> list)
{
ObjectWithHierarchy item = node.Tag as ObjectWithHierarchy;
foreach (var childItem in list.FindAll(i => i.ParentId == item.Id))
{
// create the child node
TreeNode childNode = new TreeNode();
childNode.Text = childItem.Name;
childNode.Tag = childItem;
// load children, if there are any
LoadChildNodes(childNode, list);
// add it to its parent nodes collection
node.Nodes.Add(childNode);
}
}
有些第三方控件如果知道 Id 和 ParentId 属性,就“知道”如何显示层次结构。
编辑:刚刚注意到您正在使用 ASP.NET,并且代码用于 winforms TreeView ,但概念大致相同。
关于c# - 我如何从数据表到asp.net c#中的层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5076375/