我正在尝试填充一个支持以下递归关系的多维数组(DATA来自数据库表)。
这个多维数组将用于生成下面的列表。我在VB.NET中使用多维数组的经验很少。如果有任何帮助,我将不胜感激。如果你认为有更好的方法来实现这一点,请告诉我。
数据
ID NAME PARENTID
10 Bobby Brown 50
20 Dave Matthew 80
30 Sergey Boostad 50
40 Linda View 50
50 Bill Lumberg
60 Rina Gina 50
70 Ben Thompson 100
80 Maria Tree 50
90 Gustav Duffield 80
100 Jon Theodore
110 Cedric Loomis 100
120 Jeremy Oscar 100
输出(实现)
[50] - Bill Lumberg
[10] - Bobby Brown
[30] - Sergey Boostad
[40] - Linda View
[60] - Rina Gina
[80] - Maria Tree
[20] - Dave Matthew
[90] - Gustav Duffield
[100] - Jon Theodore
[70] - Ben Thompson
[110] - Cedric Loomis
[120] - Jeremy Oscar
要在内存中存储树,可以创建一个类,如下所示:
Public Class NameNode
Public Sub New(name As String)
Me.Name = name
End Sub
Public Property Name As String
Public Level As Integer
Public Property Children As New List(Of NameNode)
End Class
然后,你可以这样使用它:
Dim bill As New NameNode("Bill Lumberg")
bill.Children.Add(New NameNode("Bobby Brown")
bill.Children.Add(New NameNode("Sergey Boostad")
要从平面DataSet
填充它,您需要制作一个递归方法,例如:
Public Function BuildNode(data As DataSet, nameId As Integer, level As Integer), As NameNode
Dim node As New NameNode()
node.Level = level
' Find name with the ID in the dataset and set the node's name property accordingly
Dim childIds As New List(Of Integer)
' Search Get a list of all the name ID's that have the current ID as their parent
For Each i As Integer In childIds
node.Children.Add(BuildNode(data, i, level + 1))
Next
Return node
End Function
然后你可以通过这样称呼它来建立整个Bill Lumberg分支机构:
Dim bill As NameNode = BuildNode(data, 50, 0)