ArrayList in Visual Basic .NET
The ArrayList is one of the popular date type of the collections that the .NET Framework uses extensively
This ArryList can size dynamically, you do not have to specify the size of the array. It grows dynamically as you add elements to it
Lets see how we create the ArrayList and add elements to it
Module Module1 Sub Main() Dim grad_student1 As Student grad_student1.FirstName = "John" grad_student1.LastName = "Doe" grad_student1.DateOfBirth = "01-03-1980" Dim grad_student2 As Student grad_student2.FirstName = "Mark" grad_student2.LastName = "Anthony" grad_student2.DateOfBirth = "21-06-1982" Dim list As New ArrayList list.Add(grad_student1) list.Add(grad_student1) End Sub Public Structure Student Public FirstName As String Public LastName As String Public DateOfBirth As Date Public ReadOnly Property GetName() As String Get Return FirstName + " " + LastName End Get End Property End Structure End Module
Code explanation
Line 15: I have created the ArrayList
here
Line 17: Add the element to list
object
I have created the Student structure from line 23.
Iterating the ArrayList
I am using For…Each loop iterate the ArrayList
For Each obj In list Dim stu As Student = CType(obj, Student) Console.WriteLine(stu.GetName()) Next
Code explanation
Line 2: Using CType
to cast the ArrayList
object to Student Structure
Line 3: Once You cast the object you can acres it propertiesprperties
Deleting item from ArrayList
To delete item from ArrayList you can use two methods
1 remove() –
You have to pass object as the parameter and it will delete the first occurrence of the object from ArrayList
2 removeAt()
Here you have to pass the index of the item to be deleted
list.RemoveAt(1) 'list.Remove(grad_student2)