按树级别解析分层自连接表?
如您所见,我有一个自引用类别表:
我想解析此表以找出每个类别的树级别。例如,如果根节点级别为 0,则 CPU、硬盘、VGA 和 RAM 处于级别 1,依此类推。我该怎么办?
我创建了一个字典来放置每个类别 ID 及其级别:
Dictionary<int, int> dic = new Dictionary<int, int>();
键是 CategoryId,值是级别。 请帮我如何填写字典?
I have a self referential category table as you see:
I want to parse this table to find out tree level for each category. for example if root node level is 0 then CPU and Hard Drive and VGA and RAM are in level 1 and so on. how can I handle that?
I created a dictionary to put each category ID and its Level:
Dictionary<int, int> dic = new Dictionary<int, int>();
the Key is CategoryId and Value is Level.
please help me how can I Fill the Dictionary?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法在单个 LINQ 查询中轻松完成此操作。你应该使用递归。使用 C# 编写递归函数或在数据库中使用递归 CTE。
对于C#解决方案:
调用如下:
You can't do this easily in a single LINQ query. You should use recursion. Either write a recursive function in C# or use a recursive CTE in the database.
For the C# solution:
Call as follows:
我建议您使用 with 关键字来使用递归通用表表达式。看看MSDN 上的这篇文章和我自己的问题此处。
I suggest you use a recursive Common Table Expression using the with keyword. Have a look at this article on MSDN and my own question here.
我同意前面的回答;您无法进行神奇的查询来获得树级别。像这样的层次结构通常更适合使用嵌套集合结构而不是父指针:
http://en.wikipedia .org/wiki/Nested_set_model
本文向您展示了处理嵌套集数据的一些常见查询:
http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
I agree with the previous answers; you can't do a magical query that will give you the tree level. Hierarchies like this are often better served with a nested set structure rather than a parent pointer:
http://en.wikipedia.org/wiki/Nested_set_model
This article shows you some common queries for working with nested set data:
http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/