home *** CD-ROM | disk | FTP | other *** search
- Imports System.Globalization
- Imports System.IO
- Imports Microsoft.Win32
-
- Module MainModule
-
- Sub Main()
- ' Run one of the Textxxxx procedures below by uncommenting only one statement
-
- 'TestArrays()
- 'TestArraysWithNonZeroLBound()
- 'TestArrayCopySort()
- 'TestArraySearches()
- 'TestJaggedArray()
- 'TestBitArray()
- 'TestStack()
- 'TestQueue()
- 'TestArrayList()
- 'TestHashtable()
- 'TestSortedList()
- 'TestCollectionPerformance()
- 'TestStringCollection()
- 'TestStringDictionary()
- 'TestReadOnlyCollectionBase()
- 'TestCollectionBase()
- 'TestDictionaryBase()
-
- ' These statements are usuful when running inside Visual Studio.NET
- Console.WriteLine("")
- Console.WriteLine(">>> Press Enter to terminate the program <<<")
- Console.ReadLine()
- End Sub
-
- ' this procedure tests arrays
-
- Sub TestArrays()
- ' An array initialized with the powers of 2.
- Dim intArr() As Integer = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512}
- ' Non-initialized 2-dimensional array
- Dim lngArr(10, 20) As Long
- ' An empty array
- Dim dblArr() As Double
-
- ' Create and initialize an array on the fly.
- Dim ValueArray() As Long
- ValueArray = New Long() {2, 3, 5, 9}
-
- ' test for an empty array
- If dblArr Is Nothing Then
- ReDim dblArr(100)
- End If
-
- ' number of dimension
- Console.WriteLine(lngArr.Rank) ' => 2
- ' lngArr has 11*21 elements.
- Console.WriteLine(lngArr.Length) ' => 231
-
- Console.WriteLine(lngArr.GetLength(0)) ' => 11
- Console.WriteLine(lngArr.GetLowerBound(1)) ' => 0
- Console.WriteLine(lngArr.GetUpperBound(1)) ' => 200
- End Sub
-
- ' this procedure tests arrays with LBound other than zero
-
- Sub TestArraysWithNonZeroLBound()
- ' Create a bi-dimensional array that is equivalent
- ' to the following VB6 declaration
- ' Dim(1 To 5, -10 To 10) As Integer
-
- ' Prepare an auxiliary array with the length along each direction.
- Dim lengths() As Integer = {5, 21}
- ' Prepare an auxiliary array with the starting index along each direction.
- Dim lbounds() As Integer = {1, -10}
- ' create a generic Array object from CreateInstance shared method.
- Dim arrObj As Array = Array.CreateInstance(GetType(Integer), lengths, lbounds)
-
- ' assign it to an array with the right rank
- Dim arr(,) As Integer = CType(arrObj, Integer(,))
-
- ' Prove that it worked.
- Console.WriteLine(arr.GetLowerBound(0)) ' => 1
- Console.WriteLine(arr.GetUpperBound(0)) ' => 5
- Console.WriteLine(arr.GetLowerBound(1)) ' => -10
- Console.WriteLine(arr.GetUpperBound(1)) ' => 10
-
- ' assign an element and read it back.
- arr(1, -1) = 1234
- Console.WriteLine(arr(1, -1)) ' => 1234
- End Sub
-
- ' this procedure tests array copying and sorting
-
- Sub TestArrayCopySort()
- ' Create and initialize an array (10 elements).
- Dim sourceArr() As Integer = {1, 2, 3, 5, 7, 11, 13, 17, 19, 23}
- ' Create the destination array (must be same size or larger).
- Dim destArr(20) As Integer
- ' Copy the source array into the second half of the destination array.
- sourceArr.CopyTo(destArr, 10)
- ' prove that it worked - elements 10-19 are non-zero.
- Dim i As Integer
- For i = 0 To UBound(destArr)
- Console.WriteLine(CStr(i) & " => " & destArr(i))
- Next
-
- Dim targetArray(100) As Integer
- Dim rand As New Random()
- For i = 0 To 100
- targetArray(i) = rand.Next(-1000, 1000)
- Next
- ' Sort only elements [10,100] of the targetArray.
- ' Second argument is starting index, last argument is length of the subarray.
- Array.Sort(targetArray, 10, 91)
- ' display result
- Console.Write("Elements 0-9 are unsorted: ")
- For i = 0 To 9
- Console.Write(CStr(targetArray(i)) & " ")
- Next
- Console.WriteLine("")
- Console.Write("Elements 10-100 are sorted: ")
- For i = 10 To 100
- Console.Write(CStr(targetArray(i)) & " ")
- Next
- Console.WriteLine("")
-
- ' sort structures using a parallel key array
-
- ' Create a test array.
- Dim employees() As Employee = { _
- New Employee("Joe", "Doe", #3/1/2001#), _
- New Employee("Robert", "Smith", #8/12/2000#), _
- New Employee("Ann", "Douglas", #11/1/1999#)}
-
- ' Create a parallel array of hiring dates.
- Dim hireDates(UBound(employees)) As Date
- Dim j As Integer
- For j = 0 To employees.Length - 1
- hireDates(j) = employees(j).HireDate
- Next
- ' Sort the array of Employees using HireDates to provide the keys.
- Array.Sort(hireDates, employees)
- ' Prove that the array is sorted on the HireDate field.
- For i = 0 To employees.Length - 1
- Console.WriteLine(employees(i).Description)
- Next
- Console.WriteLine("")
-
- ' Add a fourth employee.
- ReDim Preserve employees(3)
- employees(3) = New Employee("Chris", "Doe", #5/9/2000#)
- ' Extend the key array as well รป no need to re-initialize it.
- ReDim Preserve hireDates(3)
- hireDates(3) = employees(3).HireDate
- ' Re-sort the new, larger array.
- Array.Sort(hireDates, employees)
- ' Prove that the array is sorted on the HireDate field.
- For i = 0 To employees.Length - 1
- Console.WriteLine(employees(i).Description)
- Next
- Console.WriteLine("")
-
- ' make both arrays larger.
- ReDim Preserve employees(10)
- ReDim Preserve hireDates(10)
-
- ' Sort only the portion actually used.
- Array.Sort(hireDates, employees, 0, 4)
- ' Prove that the array is sorted on the HireDate field.
- For i = 0 To 10
- Console.WriteLine(employees(i).Description)
- Next
-
- ' copy a sub array
- Dim intArr() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
- Dim intArr2(20) As Integer
- ' Copy the entire source array into the first half of target array.
- Array.Copy(intArr, intArr2, 10)
- For i = 0 To UBound(intArr2)
- Console.Write(CStr(intArr2(i)) & " ") ' => 1 2 3 4 5 6 7 8 9 10 0 0 0 0 ...
- Next
- Console.WriteLine("")
-
- ' Copy elements at index 5-9 to the end of destArr.
- Array.Copy(intArr, 5, intArr2, 15, 5)
- ' This is the first element that has been copied.
- Console.WriteLine(intArr2(15)) ' => 6
-
- ' This Copy operation succeeds even if array types are different.
- Dim intArr3() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
- Dim lngArr3(20) As Long
- Array.Copy(intArr3, lngArr3, 10)
-
- ' This Copy operation fails with TypeMismatchException.
- ' (But you can carry it out with an explicit For loop.)
- Dim lngArr4() As Long = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
- Dim intArr4(20) As Integer
- ' Next statement throws a TypeMismatchException (narrowing conversion)
- Try
- Array.Copy(lngArr4, intArr4, 10)
- Catch ex As Exception
- Console.WriteLine(ex.Message)
- End Try
-
- Dim lngArr5() As Long = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
- ' Delete element at index 4.
- Array.Copy(lngArr5, 5, lngArr5, 4, 5)
- ' Complete the delete operation by clearing the last element.
- Array.Clear(lngArr5, lngArr5.GetUpperBound(0), 1)
- ' Now the array contains: {1, 2, 3, 4, 6, 7, 8, 9, 10, 0}
- For i = 0 To UBound(lngArr5)
- Console.Write(CStr(lngArr5(i)) & " ") ' => 1, 2, 3, 4, 6, 7, 8, 9, 10, 0
- Next
- Console.WriteLine("")
- Console.WriteLine("")
-
- ' Show that arrays are stored in rowwise fashion.
- Dim souArr(,) As Integer = {{1, 2, 3}, {4, 5, 6}}
- Dim desArr(2, 1) As Integer
- Array.Copy(souArr, desArr, 6)
- For i = 0 To 2
- For j = 0 To 1
- Console.WriteLine("desArr({0},{1}) = {2}", i, j, desArr(i, j))
- Next
- Next
- Exit Sub
- End Sub
-
- ' generic routine that deletes an element in any type of array.
-
- Sub ArrayDeleteElement(ByVal arr As Array, ByVal index As Integer)
- ' Shift elements from arr(index+1) to arr(index).
- Array.Copy(arr, index + 1, arr, index, UBound(arr) - index)
- ' Clear the last element.
- arr.Clear(arr, arr.GetUpperBound(0), 1)
- End Sub
-
- ' A generic routine that inserts an element in any type of array.
-
- Sub ArrayInsertElement(ByVal arr As Array, ByVal index As Integer, Optional ByVal newValue As Object = Nothing)
- ' shift elements from arr(index) to arr(index+1) to make room.
- Array.Copy(arr, index, arr, index + 1, arr.Length - index - 1)
- ' Assign the element using the SetValue method
- arr.SetValue(newValue, index)
- End Sub
-
- ' this procedure tests array searches
-
- Sub TestArraySearches()
- Dim strArr() As String = {"Robert", "Joe", "Ann", "Chris", "Joe"}
- ' search for the "Ann" value
- Console.WriteLine(Array.IndexOf(strArr, "Ann")) ' => 2
- ' Note that string searches are case-sensitive.
- Console.WriteLine(Array.IndexOf(strArr, "ANN")) ' => -1
-
- ' searches for all the occurrences of the "Joe" string.
- Dim index As Integer = -1
- Do
- ' Search next occurrence.
- index = Array.IndexOf(strArr, "Joe", index + 1)
- ' Exit the loop if not found.
- If index = -1 Then Exit Do
- Console.WriteLine("Found at index " & index.ToString)
- Loop
-
- ' A revised version of the search loop, that searches
- ' from higher indices towards the beginning of the array.
- index = strArr.Length
- Do
- index = Array.LastIndexOf(strArr, "Joe", index - 1)
- If index = -1 Then Exit Do
- Console.WriteLine("Found at index " & index.ToString)
- Loop
-
- ' Binary search on a sorted array
- Dim strArr2() As String = {"Ann", "Chris", "Joe", "Robert", "Sam"}
- Console.WriteLine(Array.BinarySearch(strArr2, "Chris")) ' => 1
-
- ' an unsuccessful search
- index = Array.BinarySearch(strArr2, "David")
- If index >= 0 Then
- Console.WriteLine("Found at index " & index.ToString)
- Else
- ' Negate the result to get the index for insertion point.
- index = Not index
- Console.WriteLine("Not Found. Insert at index " & index.ToString)
- ' => Not found. Insert at index 2
- End If
-
- End Sub
-
- ' this procedure tests arrays of arrays
-
- Sub TestJaggedArray()
- ' Initialize an array of arrays.
- Dim arr()() As String = {New String() {"a00"}, _
- New String() {"a10", "a11"}, _
- New String() {"a20", "a21", "a22"}, _
- New String() {"a30", "a31", "a32", "a33"}}
-
- ' Show how you can reference an element.
- Console.WriteLine(arr(3)(1)) ' => a31
-
- ' Assign an entire row of elements.
- arr(0) = New String() {"a00", "a01", "a02"}
-
- ' Read an element just added.
- Console.WriteLine(arr(0)(2)) ' => a02
-
- ' Expand one of the elements.
- ReDim Preserve arr(1)(3)
- ' Assign the new elements (now Nothing)
- arr(1)(2) = "a12"
- arr(1)(3) = "a13"
- ' Read back one of them
- Console.WriteLine(arr(1)(2)) ' => a12
- End Sub
-
- ' this procedure tests the BitArray class
-
- Sub TestBitArray()
- ' Provide the number of elements (all initialized to False).
- Dim ba As New BitArray(1024)
- ' Provide the number of elements, and initialize then to a value.
- Dim ba2 As New BitArray(1024, True)
-
- ' Initialize it from an array of Boolean, Byte, or Integer.
- Dim boolArr(1023) As Boolean
- ' ... (initialize the boolArr array)...
- Dim ba3 As New BitArray(boolArr)
-
- ' Initialize it from another BitArray object.
- Dim ba4 As New BitArray(ba)
-
- ' retrieve number of elements.
- Console.WriteLine(ba.Count) ' => 1024
- Console.WriteLine(ba.Length) ' => 1024
-
- ' Set element at index 100 and read it back.
- ba.Set(9, True)
- Console.WriteLine(ba.Get(9)) ' => True
-
- ' Move all the elements back to an Integer array.
- Dim intArr(31) As Integer
- ' Second argument is the index where the copy begins in target array.
- ba.CopyTo(intArr, 0)
- Console.WriteLine(intArr(0)) ' => 512
-
- ' complements all the bits in ba
- ba.Not() ' no arguments
- ' AND all the bits in ba with the complement of all the bits in ba2.
- ba.And(ba2.Not)
- ' Set all the bits to True.
- ba.SetAll(True)
-
- ' count how many 1's are in this BitArray
- Dim b As Boolean
- Dim TrueCount As Integer
- For Each b In ba
- If b Then TrueCount += 1
- Next
- Console.Write("Found " & TrueCount.ToString & " True values.")
- End Sub
-
- ' this procedure tests the Stack class
-
- Sub TestStack()
- ' Define a stack with initial capacity of 100 elements.
- Dim st As New Stack(100)
-
- ' Push three values onto the stack.
- st.Push(10)
- st.Push(20)
- st.Push(30)
- ' Pop the value on top of the stack and display its value.
- Console.WriteLine(st.Pop) ' => 30
- ' Read the value on top of the stack without popping it.
- Console.WriteLine(st.Peek) ' => 20
- ' Now pop it.
- Console.WriteLine(st.Pop) ' => 20
- ' Determine how many elements are now in the stack.
- Console.WriteLine(st.Count) ' => 1
- Console.WriteLine(st.Pop) ' => 10
- ' Check that the stack is now empty.
- Console.WriteLine(st.Count) ' => 0
-
- st.Push(10)
- ' Is the value 10 somewhere in the stack?
- If st.Contains(10) Then Console.Write("Found")
- End Sub
-
- ' this procedure tests the Queue object
-
- Sub TestQueue()
- Dim qu As New Queue(100)
- ' Insert three values in the queue.
- qu.Enqueue(10)
- qu.Enqueue(20)
- qu.Enqueue(30)
- ' Extract the first value and display it.
- Console.WriteLine(qu.Dequeue) ' => 10
- ' Read the next value but don't extract it.
- Console.WriteLine(qu.Peek) ' => 20
- ' Extract it.
- Console.WriteLine(qu.Dequeue) ' => 20
- ' Check how many items are still in the queue.
- Console.WriteLine(qu.Count) ' => 1
- ' Extract the last element and check that the queue is now empty.
- Console.WriteLine(qu.Dequeue) ' => 30
- Console.WriteLine(qu.Count) ' => 0
- End Sub
-
- ' this procedure tests the ArrayList object
-
- Sub TestArrayList()
- ' Create an ArrayList with initial capacity of 1000 elements.
- Dim al As New ArrayList(1000)
-
- ' Create an ArrayList with 100 elements equal to a null string.
- al = ArrayList.Repeat("", 100)
-
- ' Ensure you start with an empty ArrayList.
- al.Clear()
- ' Append the elements "Joe" and "Ann" at the end of the ArrayList.
- al.Add("Joe")
- al.Add("Ann")
- ' Insert "Robert" item at the beginning of the list (Index is zero-based).
- al.Insert(0, "Robert")
- ' Remove "Joe" from the list.
- al.Remove("Joe")
- ' Remove the first element of the list ("Robert" in this case).
- al.RemoveAt(0)
-
- ' two ways to remove all the elements equal to a given value
-
- ' Using the IndexOf method
- Do While al.IndexOf("element to remove") >= 0
- al.Remove("element to remove")
- Loop
-
- ' Same as previous one, but uses the Contains method.
- Do While al.Contains("element to remove")
- al.Remove("element to remove")
- Loop
-
- ' test the ArrayListJoin function
- Dim al2 As New ArrayList()
- al2.Add("Frank")
- al2.Add("Lee")
- al2.Add("Nick")
-
- al = ArrayListJoin(al, al2)
- Dim o As Object
- For Each o In al
- Console.Write(o) ' => Ann Frank Lee Nick
- Console.Write(" ")
- Next
- Console.WriteLine("")
-
- ' Insert all the items of AL2 at the beginning of current ArrayList.
- al.InsertRange(0, al2)
- For Each o In al
- Console.Write(o) ' => Frank Lee Nick Ann Frank Lee Nick
- Console.Write(" ")
- Next
- Console.WriteLine("")
-
- ' Delete the last 4 elements (Assumes there are >= 4 elements).
- al.RemoveRange(al.Count - 4, 4)
- For Each o In al
- Console.Write(o) ' => Frank Lee Nick
- Console.Write(" ")
- Next
- Console.WriteLine("")
-
- ' Extract elements to an Object array (never raises an error).
- Dim objArr() As Object = al.ToArray()
- ' Extract elements to a String array (might throw an InvalidCastException.)
- ' (Requires CType if Option Strict is on.)
- Dim strArr() As String = CType(al.ToArray(GetType(String)), String())
- For Each o In strArr
- Console.Write(o) ' => Frank Lee Nick
- Console.Write(" ")
- Next
- Console.WriteLine("")
-
- ' Same as above, but uses the CopyTo method.
- ' (Note that the target array must be large enough.)
- Dim strArr2(al.Count) As String
- al.CopyTo(strArr2)
-
- ' Copy only items [1,2], starting at element 4 in the target array.
- Dim strArr3() As String = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
- ' Syntax is: sourceIndex, target, destIndex, count.
- al.CopyTo(0, strArr3, 4, 2)
- For Each o In strArr3
- Console.Write(o) ' => 0 1 2 3 Lee Nick 6 7 8 9
- Console.Write(" ")
- Next
- Console.WriteLine("")
- End Sub
-
- ' a reusable function that merges two ArrayList objects
-
- Function ArrayListJoin(ByVal al1 As ArrayList, ByVal al2 As ArrayList) As ArrayList
- ' Note how we avoid time-consuming reallocations.
- ArrayListJoin = New ArrayList(al1.Count + al2.Count)
- ' Append the items in the two ArrayList arguments.
- ArrayListJoin.AddRange(al1)
- ArrayListJoin.AddRange(al2)
- End Function
-
- ' this procedure tests HashTable objects
-
- Sub TestHashtable()
- ' Default load factor and initial capacity.
- Dim ht As New Hashtable()
- ' Default load factor and specified initial capacity.
- Dim ht2 As New Hashtable(1000)
- ' Specified initial capability and custom load factor.
- Dim ht3 As New Hashtable(1000, 0.8)
-
- ' Decrease the load factor of the current Hashtable.
- ht = New Hashtable(ht, 0.5)
-
- ' Syntax for Add method is .Add(key, value).
- ht.Add("Joe", 12000)
- ht.Add("Ann", 13000)
- ' Referencing a new key creates an element.
- ht.Item("Robert") = 15000
- ' Item is the default member, so you can omit its name.
- ht("Chris") = 11000
- Console.Write(ht("Joe")) ' => 12000
- ' The Item property lets you overwrite an existing element.
- ' (Note that you need CInt if Option Strict is off.
- ht("Ann") = CInt(ht("Ann")) + 1000
- ' Note that keys are compared in case-insensitive mode,
- ' thus the following statement creates a *new* element.
- ht("ann") = 15000
- ' Reading a non-existing element doesn't create it.
- Console.WriteLine(ht("Lee")) ' Doesn't display anything.
-
- ' Remove an element given its key.
- ht.Remove("Chris")
- ' How many elements are now in the hashtable?
- Console.WriteLine(ht.Count) ' => 4
-
- ' Adding an element that exists already throws an exception.
- Try
- ht.Add("Joe", 11500)
- Catch ex As ArgumentException
- Console.WriteLine(ex.Message)
- End Try
-
- ' display elements in the Hashtable
- Dim de As DictionaryEntry
- For Each de In ht
- Console.WriteLine("ht('" & de.Key.ToString & "') = " & de.Value.ToString)
- Next
-
- ' Display all the keys in the hashtable.
- Dim o As Object
- For Each o In ht.Keys ' Use ht.Values for all the values.
- Console.WriteLine(o)
- Next
-
- ' create a case-sensitive Hashtable
- Dim ciht As Hashtable = _
- Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable()
- Try
- ' the second statement causes an exception.
- ciht.Add("ann", 1)
- ciht.Add("ANN", 2)
- Catch ex As Exception
- Console.WriteLine(ex.message)
- End Try
- End Sub
-
- ' this procedure tests a SortedList object
-
- Sub TestSortedList()
- ' A SortedList with default capacity (16 entries).
- Dim sl1 As New SortedList()
- ' A SortedList with specified initial capacity.
- Dim sl2 As New SortedList(1000)
-
- ' A SortedList initialized with all the elements in an IDictionary object.
- Dim ht As New Hashtable()
- ht.Add("Robert", 100)
- ht.Add("Ann", 200)
- ht.Add("JOE", 300)
- ht.Add("joe", 400)
- Dim sl3 As New SortedList(ht)
- ' display the elements in the SortedList
- Dim de As DictionaryEntry
- For Each de In sl3
- Console.WriteLine("sl3('" & de.Key.ToString & "') = " & de.Value.ToString)
- Next
- Console.WriteLine("")
-
- ' A SortedList that sorts elements through a custom IComparer.
- Dim sl4 As New SortedList(New ReverseStringComparer())
-
- ' A SortedList that loads all the elements in a Hashtable and
- ' sorts them with a custom IComparer object.
- Dim sl5 As New SortedList(ht, New ReverseStringComparer())
- For Each de In sl5
- Console.WriteLine("sl5('" & de.Key.ToString & "') = " & de.Value.ToString)
- Next
- Console.WriteLine("")
-
- ' create a case-insensitive sortedlist
- Dim sl6 As SortedList = _
- Specialized.CollectionsUtil.CreateCaseInsensitiveSortedList()
- sl6.Add("ann", 100)
- sl6.Add("BOB", 200)
- For Each de In sl6
- Console.WriteLine("sl5('" & de.Key.ToString & "') = " & de.Value.ToString)
- Next
- ' prove that you can't add two elements whose key differs only for its case.
- Try
- sl6.Add("bob", 200)
- Catch ex As Exception
- Console.WriteLine(ex.Message)
- End Try
- End Sub
-
- ' this procedure compares the performance of a few collection-like objects
-
- Sub TestCollectionPerformance()
- Const numElements As Integer = 100000
- Dim al As New ArrayList(numElements)
- Dim startTime As Date
- Dim i As Integer
-
- ' create an array of CStr(n) values, so that the CStr() function doesn't
- ' affect benchmarks
- Dim num(numElements) As String
- For i = 0 To numElements
- num(i) = CStr(i)
- Next
-
- ' load strings into an ArrayList
- startTime = Now
- For i = 1 To numElements
- al.Add(num(i))
- Next
- Console.WriteLine("ArrayList: " & Now.Subtract(startTime).ToString & " secs.")
- ' clear memory before running another benchmark
- al = Nothing
- GC.Collect()
-
- ' load strings into a HashTable
- Dim ht As New Hashtable(numElements)
- startTime = Now
- For i = 1 To numElements
- ht.Add(num(i), num(i))
- Next
- Console.WriteLine("HashTable: " & Now.Subtract(startTime).ToString & " secs.")
- ' clear memory before running another benchmark
- al = Nothing
- GC.Collect()
-
- ' load strings into a SortedList
- Dim sl As New SortedList(numElements)
- startTime = Now
- For i = 1 To numElements
- sl.Add(num(i), num(i))
- Next
- Console.WriteLine("SortedList: " & Now.Subtract(startTime).ToString & " secs.")
- ' clear memory before running another benchmark
- al = Nothing
- GC.Collect()
-
- ' load strings into a StringCollection
- Dim sc As New Specialized.StringCollection()
- startTime = Now
- For i = 1 To numElements
- sc.Add(num(i))
- Next
- Console.WriteLine("StringCollection: " & Now.Subtract(startTime).ToString & " secs.")
- ' clear memory before running another benchmark
- al = Nothing
- GC.Collect()
-
- ' load strings into a StringDictionary
- Dim sd As New Specialized.StringDictionary()
- startTime = Now
- For i = 1 To numElements
- sd.Add(num(i), num(i))
- Next
- Console.WriteLine("StringDictionary: " & Now.Subtract(startTime).ToString & " secs.")
- ' clear memory before running another benchmark
- al = Nothing
- GC.Collect()
- End Sub
-
- ' this procedure tests a StringCollection object
-
- Sub TestStringCollection()
- ' Create a StringCollection (no support for initial capability).
- Dim sc As New System.Collections.Specialized.StringCollection()
-
- ' Fill it with month names in current language, in one operation.
- ' (We leverage the DateFormatInfo object's MonthNames method, which
- ' returns an array of strings, which in turn implements IList interface.)
- sc.AddRange(DateTimeFormatInfo.CurrentInfo.MonthNames())
-
- ' Display the StringCollection contents.
- Dim s As String
- For Each s In sc
- Console.Write(s & " ")
- Next
- Console.WriteLine("")
-
- ' A temporary ArrayList that wraps around the StringCollection object.
- Dim al As ArrayList = ArrayList.Adapter(sc)
- ' Sort the inner StringCollection in reverse order through the wrapper.
- al.Sort()
- al.Reverse()
- ' Destroy the wrapper object, which isn't necessary any longer.
- al = Nothing
-
- ' Display the StringCollection contents.
- For Each s In sc
- Console.Write(s & " ")
- Next
- Console.WriteLine("")
- End Sub
-
- ' this procedure tests the StringDictionary object
-
- Sub TestStringDictionary()
- Dim sd As New System.Collections.Specialized.StringDictionary()
- sd.Add("Ann", "Marketing")
- sd.Add("Joe", "Sales")
- sd.Add("Robert", "Administration")
-
- Dim de As DictionaryEntry
- For Each de In sd
- Console.WriteLine(de.Key.ToString & " = " & de.Value.ToString)
- Next
- Console.WriteLine("")
-
- Dim nvc As New System.Collections.Specialized.NameValueCollection()
- nvc.Add("Ann", "Marketing")
- nvc.Add("Ann", "Sales")
- ' get all the strings
- Dim s As String
- For Each s In nvc.AllKeys
- Console.WriteLine(s & " = " & nvc(s))
- Next
- End Sub
-
- ' this procedure tests the ReadOnlyCollectionBase abstract class
-
- Sub TestReadOnlyCollectionBase()
- ' Display powers of 2 up to 2^20.
- Dim powers As New PowersOfTwoCollection(20)
- ' The Count property is provided by the base class.
- Console.WriteLine(powers.Count) ' => 21
-
- ' The For Each support is also provided by the base class.
- Dim n As Long
- For Each n In powers
- Console.WriteLine(n)
- Next
-
- ' Assign the value of 2^15 to a variable.
- ' Note that no casting is required, because the collection is strong-typed.
- Dim lngValue As Long = powers(15)
- End Sub
-
- ' this procedure tests the CollectionBase class
-
- Sub TestCollectionBase()
- Dim squares As New SquareCollection()
- squares.Add(New Square(10))
- squares.Add(New Square(20))
- squares.Add(New Square(30))
- squares.Create(40)
- squares.Create(50)
-
- ' The RemoveAt method is provided by the base class.
- squares.RemoveAt(0)
-
- Dim sq As Square
- For Each sq In squares
- Console.WriteLine(sq.Side) ' => 20 30 40 50
- Next
- Console.WriteLine("Total area = " & squares.TotalArea.ToString)
- End Sub
-
- ' this procedure tests the DictionaryBase class
-
- Sub TestDictionaryBase()
- Dim sq As New SquareDictionary()
- sq.Create("First", 10)
- sq.Create("Second", 20)
- sq.Create("Third", 30)
-
- Console.WriteLine(sq("Second").Side) ' => 20
- End Sub
-
- End Module
-