使用 C#/Linq 将扁平化分层数据从 SQL Server 转换为结构化 JSON 对象

2024-03-23

我正在开发一个 MVC 应用程序,它从 SQL Server 中的表中检索数据,其结构如下:

+-----------------------------------+
| Id | Name   | Hierarchy   | Depth |
|-----------------------------------|
| 01 | Justin | /           |     0 |
| 02 | Chris  | /1          |     1 |
| 03 | Beth   | /1/1        |     2 |
+-----------------------------------+

中的示例数据Hierarchy列是字符串表示形式hierarchyid数据类型,以及Depth列的计算使用hierarchyid::GetLevel() method.

使用 Entity Framework 4.1,我已将上表映射到此类:

public class Node {
    public int Id { get; set; }
    public string Name { get; set; }
    public string HierarchyPath { get; set; } // String representation of the hierarchyid
    public int Depth { get; set; }
}

我想使用此信息向用户显示层次结构的图形表示JS 可视化工具包 http://thejit.org/,这需要对数据进行结构化:

var node = {
    id: 1,
    name: 'Justin'
    children: [{
        id: 2,
        name: 'Chris',
        children: [{
            id: 3,
            name: 'Beth',
            children: []
        }]
    }]
}

我在开发将模型列表转换为结构化 JSON 对象的逻辑时遇到问题。有什么建议么?


编辑:我现在没有时间修复下面的答案,但鉴于问题中的额外信息,我怀疑您想保留Dictionary<int, HierarchicalNode>而不是一个List<HierarchicalNode>这样你就不会依赖任何订单......


我会忘记一开始的 JSON 表示,而专注于构建层次结构的内存中 POCO 表示。为此,我会使用这样的东西:

class HierarchicalNode
{
    private readonly List<HierarchicalNode> children =
        new List<HierarchicalNode>();        
    public List<HierarchicalNode> Children { get { return children; } }

    private readonly string name;
    public string Name { get { return name; } }

    private readonly int id;
    public int Id { get { return id; } }

    public HierarchicalNode(string name, int id)
    {
        this.name = name;
        this.id = id;
    }
}

然后像这样构建树:

// Make sure we get everything in a sensible order, parents before children
var query = context.Nodes.OrderBy(x => x.Depth);

var root = new HierarchicalNode("Root", 0);
foreach (var node in query)
{       
    var current = root;
    foreach (string part = node.HierarchyPath.Split(new[] {'/'},
                                   StringSplitOptions.RemoveEmptyEntries))
    {
        int parsedPart = int.Parse(part);
        current = current.Children[parsedPart - 1];
    }
    current.Children.Add(new HierarchicalNode(node.Name, node.Id));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 C#/Linq 将扁平化分层数据从 SQL Server 转换为结构化 JSON 对象 的相关文章

随机推荐