我正在尝试填充一个支持以下递归关系的多维数组(DATA来自数据库表)。
这个多维数组将用于生成下面的列表。我对VB.NET中的多维数组的经验很少。任何帮助将不胜感激。如果您认为有更好的方法来实现这一点,请告诉我。
DATA
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
OUTPUT(实现)
[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
答案 0 :(得分:2)
要将树存储在内存中,您可以创建一个这样的类:
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)