ArrayList詳細(xì)使用方法的實例 |
作者:佚名 來源:樂博網(wǎng)收集 更新時間:2007-11-28 |
Adding Objects to the ArrayListAdding 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 ArrayListTo 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 ArrayListTo 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 AscendingThere are a few different options to sorting but the basic is a simple Ascending Case Sensitive Sort: This code assumes there is a button on your form called Button1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click 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() Console.WriteLine("After Sort:") WriteElements(al) End Sub Private Sub WriteElements(ByVal al As ArrayList) Dim i As Integer For i = 0 To al.Count - 1 Console.WriteLine(CStr(al.Item(i))) Next End Sub Here is what the output will look like in the console window: Before Sort: This Is My New ArrayList Control After Sort: ArrayList Control Is My New This The sort command physically reorders each object, so you can even use the Enumerator to list each of the values and you will get the same value, shown in the next example below.
Descending ArrayList SortThis can be done by adding one line to the code above: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 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() al.Reverse() Console.WriteLine("After Sort:") WriteElements(al) End Sub Private Sub WriteElements(ByVal al As ArrayList) Dim en As IEnumerator = al.GetEnumerator While en.MoveNext Console.WriteLine(en.Current) End While End Sub |