Visual Basic PP Slides Ch 8

Chapter 8
Arrays and Collections
McGraw-Hill
Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.
Objectives
•
•
•
•
•
•
•
•
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 for matching an array element.
Combine the advantages of list box controls with arrays.
Store and look up data in multidimensional arrays.
8-2
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 referred to as a table or subscripted (index)
variable
Individual elements are treated the same as any other
variable and may be used in any statement.
8-3
Array Terms
•
Element
•
Subscript (or index)
•
• Individual item in the array
• Zero-based number used to reference the
specific elements in the array
• Must be an integer
Boundaries
• Lower Subscript, 0 by default
• Upper Subscript
8-4
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
•
Subscripts may be constants, variables, or numeric
expressions.
• Subscripts must be integers — VB rounds any
noninteger subscript.
• Subscripts always begin at zero (0)
8-6
The Declaration Statements for Arrays —
General Form
• This Dim statement allocates storage for specific
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
Dim Statement for Arrays Example(s)
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"}
Private CategoryString(10) As String
Public IdNumbersString(5) As String
8-8
Valid Subscripts
•
•
•
Subscript must reference a valid element of an
array.
VB rounds fractional subscripts.
VB throws exceptions for subscripts that are out of
range.
8-9
For Each/Next Statements
•
•
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-10
The For Each and Next Statements —
General Form
For Each ElementName [As Datatype] In ArrayName
' Statement(s) in loop.
Next [ElementName]
8-11
The For Each and Next Statements —
Example
For Each OneNameString As String In NameString
' Write one element of the array.
Debug.WriteLine(OneNameString)
Next OneNameString
8-12
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)
• 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
The Structure and End Structure Statements
— General Form
[Public|Private|Friend] Structure NameOfStructure
Dim FirstField As Datatype
Dim SecondField As Datatype
...
End Structure
8-14
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
8-15
The Structure and End Structure Statements
— Example (2 of 2)
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-16
Accessing the Elements in a Structure
Variable
•
•
•
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.
Examples
OfficeEmployee.LastNameString
OfficeEmployee.HireDate
InventoryProduct(indexInteger).DescriptionString
InventoryProduct(indexInteger).QuantityInteger
InventoryProduct(indexInteger).PriceDecimal
8-17
Including An Array In A Structure
•
•
•
Arrays can be included as elements within a Structure.
VB does not allow you to declare the number of
elements in the array within the Structure declaration.
Use the ReDim statement inside a procedure to define
the size of the array.
8-18
ReDim Code Example
' Module-level declarations.
Structure SalesDetail
Dim SaleDecimal( ) As Decimal
End Structure
Private 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
Using Array Elements for Accumulators
8-20
Debugging Array Programs
•
View the array elements in debugging time by setting a
breakpoint and view the Autos window; click the plus sign
to left of array name to view individual array elements.
8-21
Table Look up
•
•
•
•
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-22
Coding a Table Look up
8-23
Look-up Operation Logic
8-24
Using List Boxes With Arrays (1 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.
8-25
Using List Boxes With Arrays (2 of 3)
Allow the user to select
from a list and the
SelectedIndex property
can be used as the
subscript of the total array.
IndexInteger = GroupListBox.SelectedIndex
If IndexInteger <> –1 Then
8-26
Using List Boxes With Arrays (3 of 3)
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
8-27
Multidimensional Arrays
To define a two-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 with
second subscript, and use a comma to specify
the dimensions.
8-28
The Dim Statement for Two-Dimensional
Arrays — General Form
Dim ArrayName(HighestRowSubscript, Highest ColumnSubscript) As
Datatype
Dim ArrayName( , ) As Datatype = {ListOfValues}
8-29
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.
(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
Initializing Two-Dimensional Arrays
•
Initializing/Reinitializing
•
Printing a Two-Dimensional Table
•
Summing a Two-Dimensional Table
• Use nested For/Next loop.
• Use For Each/Next loop.
• Include a total field for each row and each column.
• Sum the figures in both directions (double-check
totals).
8-31
Nested For/Next Example
For RowInteger As Integer= 0 To 2
For ColumnInteger As Integer= 0 To 3
' Initialize each element.
NameString(RowInteger, ColumnInteger) = " "
Next ColumnInteger
Next RowInteger
8-32
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
Summing a Two-Dimensional Table
8-34
•
Look-up Operations for Two-Dimensional
Tables
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 will require
additional one-dimensional arrays or lists to aid in
the look-up process.
8-35
Two Dimensional Array Example
8-36
.NET Collections
• Like arrays, used to handle a group of
•
•
related data.
More sophisticated than arrays
Example collection types
–ArrayList
–SortedList
–Queue
–Stack
8-37
SortedList Collection
• Elements automatically sorted.
• Items are key – value pairs
• Elements can be referenced by key or
•
index.
Features many methods to aid in data
handling.
8-38
SortedList Properties & Methods
8-39