Using Arrays

function OpenWin(url, w, h) { if(!w) w = 400; if(!h) h = 300; window.open(url, "_new", "width=" + w + ",height=" + h + ",menubar=no,toobar=no,scrollbars=yes", true); } function Print() { window.focus(); if(window.print) { window.print(); window.setTimeout('window.close();',5000); } }
Team-Fly    

Special Edition Using Microsoft® Visual Basic® .NET
By Brian Siler, Jeff Spotts
Table of Contents
Chapter 6.  Storing Information in Variables


All the variables discussed so far have been single-instance variables. Often, however, you may find it very useful to work with arrays. An array is a group of variables of the same type, sharing the same name. In this way, processing groups of related areas is easy. For example, you might want to have a group of variables that tracks the sales in each of your company's four regions. You can declare a decimal variable for each region, plus one for the total sales across all regions, like this:

 Dim Reg1Sales, Reg2Sales As Decimal  Dim RegSales3, Reg4Sales As Decimal  Dim TotalSales As Decimal 

Then, if you want to calculate the total sales for all regions, you might use this code:

 TotalSales = Reg1Sales + Reg2Sales + Reg3Sales + Reg4Sales 

This approach isn't all that cumbersome. However, what if you have 20 regions? Or several hundred? You can see how working with large numbers of related variables could get messy very quickly.

You can greatly simplify this example by using an array. The following line of code creates an array to contain the 20 regional sales figures:

 Dim RegionalSales(19) As Decimal 

Note the array declaration looks similar to a regular variable declaration, with the addition of the number 19 in parentheses. Each element in an array is accessed using an index, which starts at zero. This is important to consider, because it means 19 is the maximum index value. So the RegionalSales array contains 20 decimal values, numbered 0 to 19.

Note

Starting in Visual Basic .NET, array indexes start at 0 and the older syntax of specifying boundaries with the To keyword is no longer supported.


Values in anarray (also known as array elements) work in assignment statements just like regular variables:

 RegionalSales(15) = 2000.00  TextBox1.Text = RegionalSales(3).ToString 

Array indexes themselves can also be variables, as in the following example, which adds all of the regional sales figures:

 Dim CurrentRegion As Integer  For CurrentRegion = 0 to 19      TotalSales = TotalSales + RegionalSales(CurrentRegion)  Next 

Note this example's use of a loop. The block of code beginning with the For instruction and ending with the Next instruction defines a group of program statements that will be repeated a certain number of times (in this case 20). Using loops makes short work of processing variable arrays. Loops are discussed in Chapter 7, "Controlling the Flow of Your Program."

Dynamic Arrays

In the previous example, when we declared the variable array RegionalSales we specified the maximum index number, 19. Because arrays are zero-based, specifying a maximum index value of 19 creates an array with 20 elements. However, at certain times you may need to declare an array variable without knowing in advance how many elements are contained within it. One example might be if the user is typing in an unknown number of values or you are reading them from a file. To change the size of an array, you can use the ReDim or ReDim Preserve statements. (The word Preserve means you want to preserve the data in the array, ReDim by itself causes the data to be lost each time array is re-dimensioned.) As an example, the following code reads a list of strings from a file, adding each string to an array.

 Dim TestFile As StreamReader = File.OpenText("inputfile.txt")  Dim NumElements As Integer = 0  Dim BunchOfStrings() As String  While TestFile.Peek <> -1        NumElements = NumElements + 1        ReDim Preserve BunchOfStrings(NumElements - 1)        BunchOfStrings(NumElements - 1) = TestFile.ReadLine()  End While  TestFile.Close()  Messagebox.Show("Number of elements in the array=" & NumElements)  Messagebox.Show("Last index number in the array=" & UBound(BunchOfStrings)) 

In the sample code, notice that no size for the BunchOfStrings array is provided, although the parentheses are still used to indicate it is a variable array. The ReDim Preserve statement within the While loop causes the array to grow as the counter variable NumElements is increased. Note that because array indexes start at zero, the count of elements in the array is always 1 greater than the maximum index value. To determine the maximum index value, you can use the Ubound function, which returns the upper boundary of an array.

Initializing an Array

In our examples up to this point, we have used the assignment statement to put values in an array. However, a new feature in Visual Basic .NET is the ability to initialize an array in the Dim statement by placing the array values in curly braces ({ }). The following example shows how an array of integers can be initialized:

 Dim PowersofTwo() As Integer = {1, 2, 4, 8, 16, 32, 64, 128} 

Initialization with curly braces can only be used when you do not specify the array boundaries explicitly. Instead, the number of array elements is set to the number of elements contained within the braces. (You can still expand or shrink the array in code using ReDim.) In the previous line of code, the resulting array PowersOfTwo contains eight elements. The element in index 0 is 1, index 1 is 2, and so on.

Sorting and Searching an Array

All variable arrays are based on the .NET Framework's built-in Array class, which means they all inherit certain functions from it. Two of the most useful of these functions are the ability to sort and search an array.

Sorting an Array

You can use the Sort function of an array to sort an array of strings or numbers. The following code sample prints the contents of an array, sorts it, and prints the array again:

 Dim strNames() As String = {"Betty", "Alphonse", "Xavier", "Susie"}  Dim CurIndex As Integer  For CurIndex = 0 To Ubound(strNames)     Debug.WriteLine(strNames(CurIndex))  Next  'The following line of code does the sorting  Array.Sort(strNames)  For CurIndex = 0 To Ubound(strNames)     Debug.WriteLine(strNames(CurIndex))  Next 

The Sort method actually moves the contents of an array, changing the elements to be indexed alphabetically. After running the sample code, Alphonse would be at index 0 and Xavier at index 3.

Note

If you want to sort in descending order, use the Sort method followed by the Reverse method.


Searching a Sorted Array

The Array class also provides the ability to search an array for an element, but the array you are searching must be sorted. The BinarySearch method simply returns the index of the element if it finds it, or a negative number if it does not.

 Dim FoundPosition As Integer  Dim SearchStudent As String = "Susie"  Array.Sort(strNames)  FoundPosition = Array.BinarySearch(strNames, SearchStudent) 

If we use the sample array data from the previous section, FoundPosition would contain the array value 2.

Arrays with Multiple Dimensions

We have seen how an array can store a value associated with an index, but what if you need to store more than one value per index? For example, earlier we stored a sales figure for each region. Suppose we needed to store more than one number for each region, such as sales for each quarter. The following statement declares a two-dimensional array:

 Dim RegionalSales(19, 3) As Decimal 

To add extra dimensions to an array, you simply specify the size of the new dimension in parentheses, separated by a comma. In the RegionalSales array, the first dimension contains 20 elements and the second dimension contains four. The following code shows how to access each element in the array:

 Dim CurrentRegion As Integer  Dim CurrentQuarter As Integer  For CurrentRegion = 0 To RegionalSales.GetUpperBound(0)      For CurrentQuarter = 0 To RegionalSales.GetUpperBound(1)          Debug.WriteLine("Sales for Region " & CurrentRegion & " Quarter " & _          CurrentQuarter & " are " & RegionalSales(CurrentRegion, CurrentQuarter))      Next  Next 

Notice in the preceding sample code we used the GetUpperBound method to determine the maximum array index for each dimension.

Note

The GetUpperBound function is zero-based, unlike the UBound function mentioned earlier. Both can be used to determine the maximum array index for a given dimension. In other words, the following statements are equivalent:

 UBound(RegionalSales,2)  RegionalSales.GetUpperBound(1) 



    Team-Fly    
    Top
     



    Special Edition Using Visual Basic. NET
    Special Edition Using Visual Basic.NET
    ISBN: 078972572X
    EAN: 2147483647
    Year: 2001
    Pages: 198

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net