Generic Tree : Generic Tree « Generics « VB.Net






Generic Tree

Generic Tree
Imports System.Collections

Public Class MainClass

   Public Shared Sub Main()
        Dim rootNode, child1 As TreeNode(Of Employee)
        rootNode = New TreeNode(Of Employee)(New Employee(111, "A"))
        child1 = rootNode.AddChild(New Employee(222, "B"))
        rootNode.AddChild(New Employee(333, "C"))
        child1.AddChild(New Employee(444, "D"))
        child1.AddChild(New Employee(555, "E"))

        Console.WriteLine(rootNode)

   End Sub


End Class


Public Class TreeNode(Of T)
    Public Data As T
    Private _childNodes As ArrayList

    Public Sub New(ByVal nodeData As T)
        Me.Data = nodeData
        Me._childNodes = New ArrayList
    End Sub

    Public ReadOnly Property Children() As TreeNode(Of T)()
        Get
            Return Me._childNodes.ToArray()
        End Get
    End Property

    Default Public ReadOnly Property Item(ByVal index As Long) As TreeNode(Of T)
        Get
            Return Me._childNodes(index)
        End Get
    End Property

    Public Function AddChild(ByVal nodeData As T) As TreeNode(Of T)
        Dim newNode As TreeNode(Of T) = New TreeNode(Of T)(nodeData)
        Me._childNodes.Add(newNode)
        Return newNode
    End Function

    Overrides Function ToString() As String
        Return Me.Data.ToString()
    End Function

End Class


Public Class Employee
    Private _id As Integer
    Private _name As String

    Public Sub New(ByVal id As Integer, ByVal name As String)
        Me._id = id
        Me._name = name
    End Sub

    Public Overrides Function ToString() As String
        Return Me._name
    End Function

End Class


           
       








Related examples in the same category

1.Define and use a generic Tree data structureDefine and use a generic Tree data structure