gpt4 book ai didi

c#-4.0 - 使用C#将平面数据结构转换为层次结构对象

转载 作者:行者123 更新时间:2023-12-01 08:08:40 25 4
gpt4 key购买 nike

我有以下平面数据结构。

ParentAttributeId AttributeId  List
----------------- ----------- ------
NULL 29 TestcaseCollection
29 30 EnclosureLeakageDielectricStrengthTest
30 31 DeviceID
30 32 ScannerOneLowChannel
30 33 ScannerTwoLowChannel
29 34 EnclosureLeakageLeakageCurrentTest
34 35 DeviceID
34 36 ScannerOneLowChannel
34 37 ScannerTwoLowChannel
29 38 PatientCircuitLeakageTest
38 39 DeviceID
38 40 ScannerOneLowChannel
38 41 ScannerTwoLowChannel
29 42 SIPSOPDielectricStrengthTest
42 44 ScannerOneHighChannel
42 45 ScannerOneLowChannel
42 46 ScannerTwoHighChannel
42 47 ScannerTwoLowChannel
29 48 SIPSOPLeakageCurrentTest
48 49 ScannerOneHighChannel
48 50 ScannerOneLowChannel
48 51 ScannerTwoHighChannel
48 52 ScannerTwoLowChannel

我需要将上面的平面数据结构转换为层次结构的对象结构,如下所示。因此,我的对象看起来像上面的“列表”列。我正在使用SQL存储过程来获取以上数据。我正在使用C#。

对象层次结构
29
|
30
| 31
| 32
| 33
|
34
| 35
| 36
|37
38

任何帮助将不胜感激。

问候
二十

最佳答案

您可以尝试这样的事情:

1)创建一个节点类

class Node
{
public int ParentId { get; private set; }
public int Id { get; private set; }
public string Label { get; private set; }
public Node Parent { get; set; }
public List<Node> Children { get; } = new List<Node>();

public Node(int parentId, int id, string lable)
{
ParentId = parentId;
Id = id;
Label = lable;
}

public void AddChild(Node child)
{
child.Parent = this;
Children.Add(child);
}

public void Trace(int indent = 1)
{
Enumerable.Range(0, indent).ToList().ForEach(i => Console.Write(" - "));
Console.WriteLine(Label);
Children.ForEach(c => c.Trace(indent + 1));
}
}

2)根据您的平面数据创建节点对象,并将其添加到字典中
var data = new List<DataRow>() {
new DataRow { ParentId = 0, Id = 1, Label = "parent" },
new DataRow { ParentId = 1, Id = 2, Label = "child 1" },
new DataRow { ParentId = 1, Id = 3, Label = "child 2" },
new DataRow { ParentId = 2, Id = 4, Label = "grand child 1" },
new DataRow { ParentId = 2, Id = 5, Label = "grand child 2" }
};

Dictionary<int, Node> nodes = data.ToDictionary(d => d.Id, d => new Node(d.ParentId, d.Id, d.Label));

3)通过遍历所有在父节点上调用AddChild的节点来构建层次结构
foreach (var node in nodes.Skip(1))
nodes[node.Value.ParentId].AddChild(node.Value);

如果在顶部节点上调用Trace(),则输出将如下所示:
 - parent
- - child 1
- - - grand child 1
- - - grand child 2
- - child 2

关于c#-4.0 - 使用C#将平面数据结构转换为层次结构对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6353033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com