按树级别解析分层自连接表?

发布于 2024-09-29 18:53:37 字数 327 浏览 3 评论 0原文

如您所见,我有一个自引用类别表:
alt text

我想解析此表以找出每个类别的树级别。例如,如果根节点级别为 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:
alt text

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

自此以后,行同陌路 2024-10-06 18:53:37

您无法在单个 LINQ 查询中轻松完成此操作。你应该使用递归。使用 C# 编写递归函数或在数据库中使用递归 CTE。

对于C#解决方案:

IEnumerable<KeyValuePair<int, int>> GetChildren(int id, int childLevel)
{
    foreach (var row in rows.Where(row => row.ParentID == id && row.ID != id))
    {
        yield return new KeyValuePair<int, int>(row.ID, childLevel);
        foreach (var x in GetChildren(row.ID, childLevel + 1))
        {
            yield return x;
        }
    }
}

调用如下:

GetChildren(0, 0);

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:

IEnumerable<KeyValuePair<int, int>> GetChildren(int id, int childLevel)
{
    foreach (var row in rows.Where(row => row.ParentID == id && row.ID != id))
    {
        yield return new KeyValuePair<int, int>(row.ID, childLevel);
        foreach (var x in GetChildren(row.ID, childLevel + 1))
        {
            yield return x;
        }
    }
}

Call as follows:

GetChildren(0, 0);
顾铮苏瑾 2024-10-06 18:53:37

我建议您使用 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.

几度春秋 2024-10-06 18:53:37

我同意前面的回答;您无法进行神奇的查询来获得树级别。像这样的层次结构通常更适合使用嵌套集合结构而不是父指针:

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/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文