Mega Code Archive

 
Categories / VB.Net Tutorial / Collections
 

Store objects in Collection and retrieve by key and index

Imports System  Public Class Employee      Private myEmpID As Integer      Public Sub New(ByVal empID As Integer)          Me.myEmpID = empID      End Sub 'New      Public Overrides Function ToString( ) As String          Return myEmpID.ToString( )      End Function 'ToString      Public Property EmpID( ) As Integer          Get              Return myEmpID          End Get          Set(ByVal Value As Integer)              myEmpID = Value          End Set      End Property  End Class 'Employee  Class Tester      Shared Sub Main( )          Dim intCollection As New Collection( )          Dim empCollection As New Collection( )          Dim empCollection2 As New Collection( )          Dim i As Integer          For i = 0 To 4              empCollection.Add(New Employee(i + 100))              intCollection.Add((i * 5))          Next i          empCollection2.Add(New Employee(1), "G")          empCollection2.Add(New Employee(2), "J")          empCollection2.Add(New Employee(3), "T")          For Each i In intCollection              Console.Write("{0} ", i.ToString( ))          Next i          Console.WriteLine( )          Console.WriteLine("Employee collection...")          Dim e As Employee          For Each e In empCollection              Console.Write("{0} ", e.ToString( ))          Next e          Console.WriteLine( )          Console.WriteLine("Employee collection 2...")          For Each e In empCollection2              Console.Write("{0} ", e.ToString( ))          Next e          Console.WriteLine( )          Dim emp As Employee          emp = empCollection2.Item("J")          Console.WriteLine(emp.ToString( ))          emp = empCollection2.Item(1)          Console.WriteLine("Index(1) retrieved empID {0}", emp.ToString( ))      End Sub   End Class 0 5 10 15 20 Employee collection... 100 101 102 103 104 Employee collection 2... 1 2 3 2 Index(1) retrieved empID 1