A friend was asking about sorting the arraylist. I’ve knocked together a sort tutorial on the object and soem of it’s abilities.
Adding Objects to the ArrayList
Adding objects is simple just use the add method:
Dim al As New ArrayList()
al.Add(“This”)
al.Add(“Is”)
al.Add(“My”)
al.Add(“New”)
al.Add(“ArrayList”)
al.Add(“Control”)
This adds 6 new objects to the arraylist.
Reading the Values of the ArrayList
To read the values you can iterate though each of the items in the Item collection like so:
Dim i As Integer
For i = 0 To al.Count – 1
Console.WriteLine(CStr(al.Item(i)))
Next
If you prefer you can use an Enumerator like this:
Dim en As IEnumerator = al.GetEnumerator
While en.MoveNext
Console.WriteLine(en.Current)
End While
Searching The ArrayList
To search for the existence of an object in the ArrayList, you can use the BinarySearch method:
Dim al As New ArrayList()
al.Add(“This”)
al.Add(“Is”)
al.Add(“My”)
al.Add(“New”)
al.Add(“ArrayList”)
al.Add(“Control”)
‘Do a case Insensitive search
Dim idx As Integer = al.BinarySearch(“my”, New CaseInsensitiveComparer())
If idx > 0 Then
MessageBox.Show(“Found at Index ” & idx)
Else
MessageBox.Show(“Not Found”)
End If
Note that we use a CaseInsensitiveComparer object above, you could also do this:
Dim idx As Integer = al.BinarySearch(“my”)
If you do not specify the IComparer implementation the default is a case sensitive compare. So the line above will return the “Not Found” message.
Sorting the ArrayList
There are a few different options to sorting but the basic is a simple Ascending Case Sensitive Sort:
Dim al As New ArrayList()
al.Add(“This”)
al.Add(“Is”)
al.Add(“My”)
al.Add(“New”)
al.Add(“ArrayList”)
al.Add(“Control”)
Console.WriteLine(“Before Sort:”)
WriteElements(al)
al.Sort()
‘ Sort descending using this: al.Reverse()
WriteElements(al)
Here’s a routine that will write the contents of the arraylist
Private Sub WriteElements(ByVal al As ArrayList)
Dim en As IEnumerator = al.GetEnumerator
While en.MoveNext
Console.WriteLine(en.Current)
End While
End Sub