7/31/2014
Objectives
Chapter 8
Arrays and Collections
Establish an array and refer to individual elements in the
array with subscripts.
Use the For Each/Next to traverse the elements of an array.
Create a structure for multiple fields of related data.
Accumulate totals using arrays.
Distinguish between direct access and indirect access of a
table.
Write a table look up f or matching an array element.
Combine the adv antages of list box controls with arrays.
Store and look up data in multidimensional arrays.
McGraw-Hill
8-2
Copyr ight 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.
Array Terms
Single-Dimension Arrays
List or series of values all referenced by the same name
Similar to list of values for list boxes and combo boxes,
without the box
Use an array to store a series of variables for later
processing.
Use an array to store multiple values.
May be ref erred to as a table or subscripted (index)
v ariable
Indiv idual elements are treated the same as any other
v ariable and may be used in any statement.
Element
Subscript (or index)
Indiv idual item in the array
Zero-based number used to ref erence the
specif ic elements in the array
Must be an integer
Boundaries
Lower Subscript, 0 by def ault
Upper Subscript
8-3
8-4
Subscripts
Array Example
nameString Array
(0)
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
(9)
Janet Baker
George Lee
Sue Li
Samuel Hoosier
Sandra Weeks
William Macy
Andy Harrison
Ken Ford
Denny Franks
Shawn James
8-5
Subscripts may be constants, variables, or numeric
expressions.
Subscripts must be integers VB rounds any
noninteger subscript.
Subscripts alw ays begin at zero (0)
8-6
7/31/2014
The Declaration Statements for Arrays
General Form
Dim Statement for Arrays Example(s)
This Dim statement allocates storage for specific
Dim NameString(25) As String
Dim BalanceDecimal(10) As Decimal
Dim ProductString(99) As String
Dim IndexInteger( ) As Integer = {1, 5, 12, 18, 20}
Dim IndexInteger As Integer( ) = {1, 5, 12, 18, 20}
Dim DepartmentsString( ) As String = {"Accounting", "Marketing"}
Priv ate CategoryString(10) As String
Public IdNumbersString(5) As String
number of elements and initializes numeric variables
to 0 and string array elements to empty string (zero
characters).
Private ArrayName(UpperSubscript) As Datatype
Dim ArrayName( ) As Datatype = {InitialValueList}
Dim ArrayName As Datatype( ) = {InitialValueList}
Elements in an array may be assigned values in the
Dim statement, cannot declare upper subscript and
initial values.
8-7
8-8
Valid Subscripts
For Each/Next Statements
Subscript must reference a valid element of an
array.
VB rounds fractional subscripts.
VB throw s exceptions for subscripts that are out of
range.
Use Loops to reference each element in the array.
For / Next or For Each/Next
VB references EACH element of the array and assigns its
value to ElementName.
Variable used for ElementName
must be same datatype as array
elements or an Object datatype.
Best to declare the variable for ElementName
as part of the For
Each statement to create a block-level variable
Makes one pass through the loop per element
Use Exit For statement within loop to exit early.
8-9
The For Each and Next Statements
General Form
8-10
The For Each and Next Statements
Example
For Each ElementName [As Datatype] In ArrayName
' Statement(s) in loop.
Next [ElementName]
For Each OneNameString As String In NameString
' Write one element of the array.
Debug.WriteLine(OneNameString)
Next OneNameString
8-11
8-12
7/31/2014
The Structure and End Structure Statements
General Form
Structures
Combine multiple fields of data to create a new
structure
Similar to defining a new data type
Combine fields into a structure using the Structure,
End Structure
Structure Declaration (by default a Structure is
Public)
[Public|Private|Friend] Structure NameOfStructure
Dim FirstField As Datatype
Dim SecondField As Datatype
.. .
End Structure
Cannot be declared inside a procedure
Generally placed at the top of a file with module-level
declarations
Can also be placed in a separate file
8-13
8-14
The Structure and End Structure Statements
Example (2 of 2)
The Structure and End Structure Statements
Example (1 of 2)
Structure Employee
Dim LastnameString As String
Dim FirstNameString As String
Dim SocialSecurityNumberString As String
Dim StreetString As String
Dim StateString As String
Dim ZipCodeString As String
Dim HireDate As Date
Dim PayCodeInteger As Integer
End Structure
Friend Structure Product
Dim DescriptionString As String
Dim ProductNumberString As String
Dim QuantityInteger As Integer
Dim PriceDecimal As Decimal
End Structure
Structure SalesDetail
Dim SaleDecimal () As Decimal
End Structure
8-15
8-16
Accessing the Elements in a Structure
Variable
Including An Array In A Structure
Each field of data in Structure is referred to as an
element of the structure.
To access elements use the dot notation similar to
that used for objects Specify Variable.Element.
Exam ples
OfficeEmployee.LastNameString
OfficeEmployee.HireDate
InventoryP roduct(indexInteger).DescriptionString
InventoryP roduct(indexInteger).QuantityInteger
InventoryP roduct(indexInteger).P riceDecimal
8-17
Arrays can be included as elements w ithin a Structure.
VB does not allow you to declare the number of
elements in the array w ithin the Structure declaration.
Use the ReDim statement inside a procedure to define
the size of the array.
8-18
7/31/2014
Using Array Elements for Accumulators
ReDim Code Example
' Module-level declarations.
Structure SalesDetail
Dim SaleDecimal( ) As Decimal
End Structure
P rivate HouseWaresSalesDetail As SalesDetail
' Inside a procedure.
' Establish the number of elements in the array.
ReDim houseWaresSalesDetail.SaleDecimal(6)
' In processing.
HouseWaresSalesDetail.SaleDecimal _
(DayIndexInteger) = CurrentDaySalesDecimal
8-19
8-20
Debugging Array Programs
Table Look up
View the array elements in debugging time by setting a
breakpoint and v iew the Autos window; click the plus sign
to lef t of array name to view indiv idual array elements.
Often, values used to identify a series of
elements are not sequential.
Use a table look up process to find the correct
element in the array.
Establish a structure and dimension an array of
the structure.
Use the Form_Load event procedure to put
numbers in table executed once as the form
is loaded into memory.
8-21
8-22
Look-up Operation Logic
Coding a Table Look up
8-23
8-24
7/31/2014
Using List Boxes With Arrays (1 of 3)
Using List Boxes With Arrays (2 of 3)
Use List Boxes or Combo Boxes rather than text
boxes to look up information in the array.
Use the list's SelectedIndex property to determine
the array subscript.
SelectedIndex property holds the position or
index of the selected list item.
Allow the user to select
f rom a list and the
SelectedIndex property
can be used as the
subscript of the total array.
IndexInteger = GroupListBox.SelectedIndex
If IndexInteger <> 1 Then
8-25
8-26
Using List Boxes With Arrays (3 of 3)
Multidimensional Arrays
SaleInteger = Integer.Parse(SaleTextBox.Text)
TotalInteger(IndexInteger) += SaleInteger
' Clear the screen fields.
GroupListBox.SelectedIndex = 1
SaleTextBox.Text = ""
Else
MessageBox.Show("Select a group number from
the list.", "Data Entry Error",
MessageBoxButtons.OK,MessageBoxIcon.Exclamation)
End If
To define a tw o-dimensional array or table
Dim statement specifies number of rows and
columns.
The row is horizontal and the column is vertical.
May specify number of elements initial values
Specify row with first subscript, column w ith
second subscript, and use a comma to specify
the dimensions.
8-27
The Dim Statement for Two-Dimensional
Arrays General Form
8-28
The Dim Statement for Two-Dimensional Arrays
Example(s)
Dim NameString(2, 3) As String
Dim NameString( , ) As String = {{"James", "Mary", "Sammie", "Sean"}, _
{"Tom", "Lee", "Leon", "Larry"}, {"Maria", "Margaret", "Jill", "John"}}
' Both statements establish an array of 12 elements.
Dim ArrayName(HighestRowSubscript, Highest ColumnSubscript ) As
Datatype
Dim ArrayName( , ) As Datatype = {ListOfValues}
8-29
(0, 0)
James
(0, 1)
Mary
(0, 2)
Sammie
(0, 3)
Sean
(1, 0)
Tom
(1, 1)
Lee
(1, 2)
Leon
(1, 3)
Larry
(2, 0)
Maria
(2, 1)
Margaret
(2, 2)
Jill
(2, 3)
John
8-30
7/31/2014
Initializing Two-Dimensional Arrays
Initializing/Reinitializing
Printing a Tw o-Dimensional Table
Summing a Tw o-Dimensional Table
Nested For/Next Example
Use nested For/Next loop.
For RowInteger As Integer= 0 To 2
For ColumnInteger As Integer= 0 To 3
' Initialize each element.
NameString(RowInteger, ColumnInteger) = " "
Next ColumnInteger
Next RowInteger
Use For Each/Next loop.
Include a total f ield for each row and each column.
Sum the f igures in both directions (double-check
totals).
8-31
8-32
Summing a Two-Dimensional Table
Printing a Two-Dimensional Table
' Print one name per line.
For Each ElementString In NameString
' Set up a line.
e.Graphics.DrawString(ElementString, PrintFont, _
Brushes.Black, HorizontalPrintLocationSingle, _
VerticalPrintLocationSingle)
' Increment the Y position for the next line.
VerticalPrintLocationSingle += LineHeightSingle
Next ElementString
8-33
Look-up Operations for Two-Dimensional
Tables
8-34
Two Dimensional Array Example
Use same techniques as for single dimensional
arrays
Direct Reference (if meaningful row and
column subscripts are available)
Table Look up
Many 2D tables used for look up w ill require
additional one-dimensional arrays or lists to aid in
the look-up process.
8-35
8-36
7/31/2014
.NET Collections
SortedList Collection
Like arrays, used to handle a group of
Elements automatically sorted.
Items are key value pairs
Elements can be referenced by key or
related data.
More sophisticated than arrays
Example collection types
index.
Features many methods to aid in data
ArrayList
SortedList
Queue
Stack
handling.
8-37
8-38
SortedList Properties & Methods
8-39