填充嵌套 ObservableCollection
我有一个类
public class Owner
{
public int OwnerId{get; set;}
public int OwnerName{get; set;}
public ObservableCollection<Owner> SubOwner{get; set;}
}
从数据库返回的数据是
Owner_Id Owner_Parent_Id
1 null
2 1
3 1
4 3
5 3
6 4
7 6
我需要用上述数据(如树结构)填充我的变量 ObservableCollection Owner 。请帮助我。
I have a class
public class Owner
{
public int OwnerId{get; set;}
public int OwnerName{get; set;}
public ObservableCollection<Owner> SubOwner{get; set;}
}
The data returned from DB is
Owner_Id Owner_Parent_Id
1 null
2 1
3 1
4 3
5 3
6 4
7 6
I need to populate my variable ObservableCollection Owner with above data(like tree structure).Please help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我理解正确的话,您想了解如何根据从数据库获取的所有者 ID 和所有者父 ID 构建非二叉树。为此,您需要单独跟踪树根(Owner 的实例)。然后,您添加一个 API 以将新的所有者添加到您的树中,该 API 仅在树根上调用。此 API 递归地遍历树,直到找到要添加到的正确父级。您还可以排列树,使其比搜索每个节点更快。
这是一个很好的教程 在 C# 中创建树。
但是,在上面的简单示例中,我不会推荐一棵树。我建议将parentID 添加到您的Owner 类中,然后使用简单的SortedList。然后,您可以轻松找到 ID,获取其父级,然后遍历,就好像您有一棵树一样。例如:
如果您想沿着树向下行走,请保留根节点的索引,然后创建第二个 SortedList其中 int 是父 ID 而不是 ID。然后,使用第二个 SortedList,WalkUpTree 变为 WalkDownTree。
If I understand you correctly, you want to learn how to build a non-binary tree from the owner ID and owner parent ID that you are getting from the database. To do this, you need to keep track of the tree root (an instance of Owner) separarely. You then add an API to add a new Owner to your tree that is only called on the tree root. This API walks the tree recursively until it finds the correct parent to add to. You can also arrange your tree so that it's faster than having to search every node.
Here's a good tutorial on creating a tree in C#.
However, in your simple example above, I would not recommend a tree. I'd recommend adding the parentID to your Owner class and then using a simple SortedList<int ID, Owner>. Then you can easily find an ID, get its parent, and traverse as if you had a tree. For example:
If you want to walk down the tree, keep the index of the root node, and then make a second SortedList<int, Owner> where the int is parent ID rather than ID. WalkUpTree then becomes WalkDownTree using the second SortedList.