Arrays

Real programmers don t use internal spaces in object names , and real programmers use arrays as elements in their solution toolkit. Arrays are a lightweight, in- memory data store. Once you know a few of the basics, arrays are easy to program. For example, your knowledge of For loops will come in very handy. This section reviews traditional array topics for classic Visual Basic developers while presenting some new information on array processing with Visual Basic .NET. The section closes with a sample that illustrates how to use arrays to consolidate data from different sources and display that data in a unified way.

Overview of Array Design

Arrays are collections of values that you can refer to with a single variable name . Just as a memory variable refers to a single value in memory, an array variable designates a collection of values in memory. Because an array is based on memory, data access and data manipulation can be very fast. In addition, arrays are lightweight. Although an array offers less functionality than a DataTable object from ADO.NET, an array has less overhead. For example, a datatable offers built-in constraints, such as primary keys. Arrays do not use primary keys, but you can add and edit values in an array. (In addition, arrays offer other features, such as sorts.)

The values, or elements, within an array can have up to 32 dimensions. An array s Rank property reflects the number of dimensions in an array. The first dimension represents rows, the second represents columns, the third represents sets of rows and columns , and so on. The dimensions within an array have a length property that reflects the number of items along a dimension. All the elements in an array typically have the same value type, such as an Integer or a Single data type designation. The type specification in an array's declaration restricts the array values. When an array must store values with different data types, you can declare the array with an Object data type. The Object data type designation permits an array to contain values with different subtypes in its elements, such as Strings and Integers .

Note  

It is good programming practice to keep the number of array dimensions low, say at one or two dimensions. As the rank (number of dimensions) of an array grows, the array s memory requirements can increase drastically. For example, an array with two dimensions with a length of 2 on each dimension and a Byte data type requires 4 bytes of memory. If the array s length stays at 2 per dimension but its rank increases to 32, the array will require 4 MB of memory!

Visual Basic .NET permits your applications to refer to the individual values, or elements, within an array by using zero-based index numbers . With classic Visual Basic, developers could select either a one-based or a zero-based index for array dimensions. You can return the maximum index value along a dimension by using the GetUpperBound method. Use a zero-based number as an argument for the GetUpperBound method to indicate the dimension for which you seek the highest index value. Because arrays in Visual Basic .NET always have a lower bound of zero, the maximum index value of an array s dimension will be 1 less than the length of that dimension. You can also use the GetLength method to return the number of items along a dimension. The GetLength method takes the same kind of argument as the GetUpperBound method.

You declare a variable referencing an array in a way that's similar to how you declare a variable for a memory variable. Use the Dim statement or an access modifier such as Private to declare an array variable. Include parentheses after the variable name to indicate that the variable represents an array of values instead of a scalar value (that is, a single value in memory). When a variable denotes an array with more than one dimension, within the parentheses, add a comma followed by a blank character for each additional dimension. Within the parentheses, following a variable name, you can optionally designate the upper index value as a zero-based number for each dimension. The following example declares an array with two dimensions and a length of 2 for each dimension. This array has a Byte data type. All four values in the array will initially equal 0 because the declaration does not assign values to the array elements. (The default value for a Byte data type is 0.)

 Dim MyArray (1, 1) as Byte 

The length of each dimension for all arrays in Visual Basic .NET is variable. You can use the ReDim statement to vary the length of an array in any dimension in the array after its initial declaration. As with classic Visual Basic, you can use the Preserve keyword to retain the values in an array when you resize. Using the Preserve keyword restricts upper-limit specifications to the last dimension. The ReDim statement is useful for reducing the memory requirements of a large array that you do not need for the lifetime of the array variable s declaration.

Note  

The ReDim statement applies only to arrays declared at the procedure level. Arrays declared for a whole module or class cannot have their dimension length respecified.

Arrays are objects in the .NET Framework, and an array variable can point at more than one array object over its lifetime. You can use the Erase statement to remove from memory the object at which an array variable points. Then you can use the ReDim statement to reassign the array variable to a new array object. You can use the ReDim and Erase statements at the procedure level only. These statements do not operate at the class or module level.

Processing a One-Dimensional Array

The first sample we will look at in this section demonstrates how to declare and manipulate a one-dimensional array. This sample will also reinforce your understanding of data types. The code consists of a couple of Sub procedures in a project started from the Empty Project template. The project s name is ArrayDemos. The first procedure has the name main , which is the default startup object for a module in an empty project. This procedure contains two Sub procedure calls, but only one lacks a comment marker ”the second Sub procedure, OneDArrayDemo .

The OneDArrayDemo procedure starts with the declaration of an array, ary_int1 . The parentheses after the array s name mark ary_int1 as pointing at a one-dimensional array of values. Notice that no commas separating values in the parentheses exist. The data type of values in the ary_int1 array must be Integer . The procedure s first line declares the array and instantiates its elements. The New keyword to the right of the equal sign (=), followed by the Integer keyword and parentheses, instantiate an array with a length of 2. The two members in the array have index values of 0 and 1. The array values (9 and 99) are delimited by commas within curly braces ( {} ).

After declaring and instantiating the ary_int1 array, the procedure displays two message boxes ”one with the type for the overall array and the other with the type for the second element in the array. A separate message box displays the data type value for each array element. When you run the procedure, the first message box shows System.Int32[] . The square brackets denote a sequence of values, and System.Int32 indicates the type of values in the sequence. This system data type corresponds to the Visual Basic .NET Integer data type. (See Table 3-1.) The second message box shows System.Int32 without any trailing brackets. This is because this message box reports the data type for a single value, the one corresponding to the second element in the ary_int1 array.

The final segment of the OneDArrayDemo procedure displays the contents of the ary_int1 array. One of the strengths of arrays is the ease with which you can process them with For loops. This final segment loops through the elements within the ary_int1 array with a single For loop. The loop starts at 0, which is always the first index value in a dimension in a Visual Basic .NET array. The loop continues until reaching the uppermost index value, 1, which the GetUpperBound method returns. The code within the loop builds a string value for display in a message box function. The code invokes the ToString method to convert the integer values within the array to strings for display in the message box. Visual Basic .NET automatically converts from an Integer data type to a String data type, but explicitly indicating the conversion saves the operating system work. In addition, if your code operates in a module with an Option Strict On statement, Visual Basic .NET raises a compile error unless you convert explicitly from Integer to String . The third message box presented by the OneDArrayDemo procedure shows the values 9 and 99 on separate lines.

 Sub main() OneDArrayDemo() 'TwoDArrayDemo() End Sub Sub OneDArrayDemo() 'Declare a one-dimensional Integer array of length 2 'and populate it with 9 and 99. Dim ary_int1() As Integer = New Integer(1) {9, 99} 'Display type for the array followed by 'an individual element within the array. MsgBox(ary_int1.GetType.ToString) MsgBox(ary_int1(1).GetType.ToString) 'Display array elements. Dim int1 As Integer Dim str1 As String For int1 = 0 To ary_int1.GetUpperBound(0) str1 = str1 & ary_int1(int1).ToString & vbCr Next MsgBox(str1) End Sub 

Processing a Two-Dimensional Array

An array with two dimensions represents a table with rows and columns. The first dimension corresponds to rows, and the second dimension points to columns in the table specified by an array. The following code sample adds two procedures to the ArrayDemos project created for the preceding sample. The first procedure, TwoDArrayDemo , illustrates various processing techniques for manipulating a two-dimensional array. In particular, the sample demonstrates how to initialize a two-dimensional array, how to resize its length, and how to add new values to an array after you resize it. The second procedure, DisplayTwoDArray , displays a two-dimensional array. This procedure accepts any array as an argument and prints the first two dimensions. Because you pass the array to this procedure as an object, you can reuse it with a two-dimensional array of any data type. You can start this second array processing sample from the main procedure. To do so, place a comment marker in front of the call to the OneDArrayDemo procedure, and remove the comment marker from the call to the TwoDArrayDemo procedure.

The TwoDArrayDemo procedure commences by initializing the ary_sng1 array. The initialization process in this sample differs from the preceding sample in two respects. First, the data type is Single in this case. (The data type was Integer in the preceding sample.) The Single data type in this sample allows the representation and computation of numbers with values to the right of a decimal point. Second, the array in this sample has two dimensions, instead of just one, as in the preceding sample. The Dim statement declaring the array uses a New constructor with nested curly braces. The outside set of curly braces applies to the overall array. The three sets of curly braces within the outside curly braces apply to each of the three rows within the two-dimensional array.

After initializing the array, the TwoDArrayDemo procedure starts to process the array. This procedure begins by calling the DisplayTwoDArray procedure. This call displays the initial values for the array in a message box. We will examine the DisplayTwoDArray procedure and its output after discussing the entire TwoDArrayDemo procedure. The remainder of the TwoDArrayDemo procedure manipulates the ary_sng1 array and displays various results. For example, the code block you are about to see shows the length of the first and second dimensions before and after the code modifies the length of the second dimension with a ReDim statement. The ReDim statement adds a new column to the array and preserves the initial values. This statement converts the table in the array from one with three rows and two columns to a table with three rows and three columns. The last three code blocks in the procedure display the array elements before and after the code populates the last column in the array. The procedure populates the last column by using a For loop to loop down the rows in the third column. In each pass through the loop, the code computes a new Single value for a row in the third column.

The DisplayTwoDArray procedure accepts an array as an argument. The procedure uses nested For loops to pass through the column values for successive rows in the array. As the procedure passes through the columns, it constructs a string value ( str1 ) with the column index and value for each column on a row. A comma and a space (", ") delimits the column index and value for the columns within a row. After finishing the processing for a row, the procedure removes the trailing command and space delimiter with the Mid function and appends a vbCr constant to separate the rows with a carriage return. Figure 3-7 contrasts the first message box for this sample with its three- by-two table, and the last message box with its three-by-three table.


Figure 3-7: With the ReDim statement, you can add a new column of values to an existing array while retaining the original values.
 Sub TwoDArrayDemo() 'Declare a two-dimensional Integer array with 'lengths of 3 and 2; populate with three two-tuples. Dim ary_sng1(,) As Single = _ New Single(2, 1) {{1.1, 2.2}, {3.3, 4.4}, {5.5, 6.6}} 'Display array elements. DisplayTwoDArray(ary_sng1) 'Display length of array dimensions before and after 'increasing the length of the last dimension; this adds 'a third column to the ary_sng1 array. MsgBox(ary_sng1.GetLength(0).ToString & ", " & _ ary_sng1.GetLength(1).ToString) ReDim Preserve ary_sng1(2, 2) MsgBox(ary_sng1.GetLength(0).ToString & ", " & _ ary_sng1.GetLength(1).ToString) 'Now, display the array elements again. DisplayTwoDArray(ary_sng1) 'Populate third column in the array. Dim int1 As Integer For int1 = 0 To ary_sng1.GetUpperBound(0) ary_sng1(int1, 2) = 10 + ((int1 + 1) / 100) Next 'Display array elements with the new values. DisplayTwoDArray(ary_sng1) End Sub Sub DisplayTwoDArray(ByVal ary_int As Array) 'Declare objects. Dim str1 As String Dim int1 As Integer Dim int2 As Integer 'Display data elements by looping through the second 'dimension elements for each first dimension element. For int1 = 0 To ary_int.GetUpperBound(0) For int2 = 0 To ary_int.GetUpperBound(1) str1 = str1 & _ "Column(" & int2.ToString & "): " & _ CStr(ary_int(int1, int2)) & ", " Next str1 = Mid(str1, 1, str1.Length - 2) & vbCr Next int1 MsgBox(str1) End Sub 

Consolidating Metadata with an Array

The last sample for processing an array that we will look at extends an earlier sample from the MetaDataLooping project. The closing demonstration from the Translating Access Data Types section contrasted Access table data types with ADO data types, and in a second listing, the sample contrasted Access table data types with Visual Basic .NET data types. The listings from that earlier sample appeared in the Output window, one after the other. But what if you want to create a single listing with Access table data types and their corresponding ADO and Visual Basic .NET data types side by side? The following sample shows how to achieve this with array processing.

This sample adds a new button ( Button4 ) to Form1 in the MetaDataLooping project. I updated the default Text property for the button to Show Data Type Comparison. The Button4_Click event procedure has the main part of the logic for the sample, but the event procedure calls the DisplayTwoDArray procedure that initially appeared in the ArrayDemos project. One simple approach to making the DisplayTwoDArray procedure available in the MetaDataLooping project is to copy from one procedure and paste the code into the other procedure. The following code listing shows only the Button4_Click event procedure because the DisplayTwoDArray procedure is not edited in any way. The Button4_Click event procedure additionally calls the ADODataType procedure, summarized earlier in the Translating Access Data Types section. Because this procedure does not change for its use here, it does not appear in the following code listing. Also, you do not need to copy the procedure into the project because I initially developed it for the project.

Much of the code in the Button4_Click event procedure is a direct copy of the material from the Button3_Click event procedure discussed in the previous section. To help you identify the fresh content for array processing, the new code appears in boldface. Starting with the declaration area, the sample will use two Integer variables , int1 and int2 , to assist with array processing. Of course, we need to declare an array to have one available for processing. The declaration of ary_str1 specifies an array containing 15 rows and 3 columns that hold string data.

After the declarations, the sample procedure makes a connection to the dbDataTypes Access database and points a Catalog variable ( cat2 ) at the database. Then the procedure points an ADOX.Table object ( tbl1 ) at the DataTypes table in the database. Recall that these steps require references to COM objects. The next segment of code in boldface illustrates how to loop through the columns of tbl1 and preserve in the ary_str1 array the column name and the ADO DataTypeEnum name matching the Access table data type. The For loop populates the first two columns of the array for each of the 15 columns in the tbl1 object. Then the procedure copies the DataTypes table from the dbDataTypes database to the DataTypes in the dsDateTypes1 object within the MetaDataLooping project. During the copying process, Visual Basic .NET automatically converts from Access data types to .NET Framework data types.

A second loop (also in bold) iterates through the local datatable and extracts the .NET Framework name for the data type of each column. The loop saves these .NET Framework names in the third column of the ary_str1 array. After looping completes, control passes to the DisplayTwoDArray procedure, which displays a message box with three columns. (See Figure 3-8.) As you can see, this message box shows the column names from the table in the Access database, along with their corresponding ADO and .NET Framework data types as the second and third column values.

click to expand
Figure 3-8: You can use arrays to consolidate multiple types of data because this output contrasts ADO and .NET Framework data types corresponding to Access data types.
Note  

The Button4_Click event procedure demonstrates the use of the += operator. Visual Basic .NET introduces this operator to classic Visual Basic developers. This operator enables you to add a constant to a memory variable. In the sample, += adds the value 1 to the int1 memory variable.

 Private Sub Button4_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button4.Click 'Declare objects. Dim cnn1 As New ADODB.Connection() Dim cat2 As New ADOX.Catalog() Dim tbl1 As ADOX.Table Dim col1 As ADOX.Column  Dim int1, int2 As Integer   Dim ary_str1(14, 2) As String  'Open ADO connection to database. cnn1.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=C:\pawvbnet\" & _ "MetaDataLooping\bin\dbDataTypes.mdb;", _ "Admin", "") 'Assign connection to catalog and open 'a table in the catalog. cat2.ActiveConnection = cnn1 tbl1 = cat2.Tables("DataTypes")  'Iterate through the columns in the table   'and decode ADO type numbers to ADO type name;   'save the column name and ADO data type in the   'first two columns of the ary_str1 array.   For Each col1 In tbl1.Columns   ary_str1(int1, int2) = col1.Name   ary_str1(int1, int2 + 1) = ADODataType(col1.Type)   int1 += 1   Next  'Fill a local dataset with a table from 'an Access database. OleDbDataAdapter1.Fill(DsDataTypes1, "DataTypes") Dim dt1 As DataTable Dim dtcol As DataColumn  'Begin by resetting int1 to its default value.   'Then, iterate through the columns in the dataset's   'table based on the original in the Access database;   'save the string representation of the .NET data type   'in the third column of the ary_str1 array.   int1 = 0   For Each dtcol In DsDataTypes1.Tables("DataTypes").Columns   ary_str1(int1, 2) = dtcol.DataType.ToString   int1 += 1   Next   'Display array elements.   DisplayTwoDArray(ary_str1)  End Sub 
 


Programming Microsoft Visual Basic. NET for Microsoft Access Databases
Programming Microsoft Visual Basic .NET for Microsoft Access Databases (Pro Developer)
ISBN: 0735618194
EAN: 2147483647
Year: 2006
Pages: 111
Authors: Rick Dobson

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