Home

Introduction to Arrays

Fundamentals of Arrays

Introduction

An array is a list of values. All values must be of the same type. The values are arranged in a consecutive manner each after another. This organizatopm makes it easy to retrieve and optionally manipulate the items.

Introduction to Creating an Array

The most fundamental formula to create an array is:

Dim variable-name(count) As data-type

Like a normal variable, an array must have a name, which is followed by parentheses. In the parentheses, specify the number of elements or items in the array. When creating an array, you must decide what type of values each element of the array would be. A simple array can be made of primitive types of values. Here is an example:

<%
    Dim classifications(4) As String
%>

Introduction to Adding Values to an Array

There are various ways you can specify the items and values of an array. One technique is to use the following formula:

Dim variable-name = New data-type() { values }

Notice that the parentheses after the data type are empty, followed by curly brackets. In the curly brackets, specify the value of each item and separate them with commas. Here is an example:

<%
    Dim days = New String() { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" }
%>

Introduction to Accessing the Members of an Array

Once the array has been created, you can access each one of its elements. To do this, type the name of the array followed by parentheses. In the parentheses, enter the position, called index, of the desired item. The first member of the array is at position, or has the index, 0. The second item has the index 1. The third item has the index 2, and so on. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<%
    Dim days = New String() { "Monday", "Tuesday", "Mayday", "Thursday", "Friday" }

    Response.Write(days(0))
    Response.Write("<br>" & days(1))
    Response.Write("<br>" & days(2))
    Response.Write("<br>" & days(3))
    Response.Write("<br>" & days(4))
%>
</body>
</html>

This would produce:

Introduction to Accessing the Members of an Array

Accessing the Items in a Loop

Since each item occupies a specific position in an array, you can use a loop to access the elements one at a time. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<%
    Dim i As Integer
    Dim days = New String() { "Monday", "Tuesday", "Mayday", "Thursday", "Friday" }

    For i = 0 To 4
        Response.Write(days(i) & "<br>")
    Next
%>
</body>
</html>

Accessing Each Item

You can also use a For Each...Next loop to access each item of the loop. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<%
    Dim day As String
    Dim days = New String() { "Monday", "Tuesday", "Mayday", "Thursday", "Friday" }

    For Each day In days
        Response.Write(day & "<br>")
    Next
%>
</body>
</html>

Specifying or Changing the Value of an Item

By accessing an item by its position, you can specify its value. In fact, if you declare an array variable as we did in our introduction (Dim SocialSciences(15) As String), you can access each element using its index and assign the desired value. Here are examples:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<title>Software Development Life Cycle</title>
</head>
<body>
<%
    Dim phase As String
    Dim phases(5) As String

    phases(0)  = "Planning"
    phases(1)  = "Analysis"
    phases(2)  = "Design"
    phases(3)  = "Implementation"
    phases(4)  = "Maintenance"

    For Each phase In phases
        Response.Write(phase & "<br>")
    Next
%>
</body>
</html>

This would produce:

Specifying or Changing the Value of an Item

On the other hand, if the values of the elements have already been created, you can access an element by its index and assign a new value to change it. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<%
    Dim i As Integer
    Dim days = New String() { "Monday", "Tuesday", "Mayday", "Thursday", "Friday" }

    Response.Write(days(0))
    Response.Write("<br>" & days(1))
    Response.Write("<br>" & days(2))
    Response.Write("<br>" & days(3))
    Response.Write("<br>" & days(4) & "<br>")

    days(2) = "Wednesday"

    For i = 0 To 4
        Response.Write("<br>" & days(i))
    Next
%>
</body>
</html>

This would display:

Specifying or Changing the Value of an Item

Primary Characteristics of an Array

Introduction to the Array Class

To support arrays, the .NET Framework provides a class named Array. The Array class is defined in the System namespace. Whenever you create or use an array, it is actually an object of type Array.

The Length of an Array

As seen in our introduction, if you declare an array variable without initializing it, you must specify the number of elements of the array. Here is the example we saw:

<%
    Dim classifications(4) As String
%>

If the array exists already, to assist you with finding out the number of elements in it, the Array class provides a read-only property named Length:

Public ReadOnly Property Length As Integer

Therefore, to know the number of items that an array contains, get the value of the Length property. If you are using a For...To...Next loop to access each element of an array, the value for the To clause will be the Length - 1.

Arrays and Procedures/Functions

Returning an Array From a Function

You can create a function that returns an array. To specify the returned type of the function, type As followed by the data type and empty parentheses. In the body of the function, you can use a situation that produces an array and returns i. Here is an example:

<script runat="server">
Function GenerateTimeWorked() As Double()
    Dim days = New Double() { 9.00, 8.50, 10.50, 8.00, 7.50, 0.00, 0.00 }

    Return days
End Function
</script>

To use the value returned by the function, you can assign it to a variable and use that variable like any array variable. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<script runat="server">
Function GenerateTimeWorked() As Double()
    Dim days = New Double() { 9.00, 8.50, 10.50, 8.00, 7.50, 0.00, 0.00 }

    Return days
End Function
</script>
<title>Exercise</title>
</head>
<body>
<%
    Dim work = GenerateTimeWorked()

    For Each day As Double In work
        Response.Write(FormatNumber(day) & "<br>")
    Next day
%>
</body>
</html>

This would produce:

Returning an Array From a Function

Passing an Array to a Procedure/Function

Like a regular variable, an array can be passed to a function. In the parentheses of the procedure or function, make sure the name of the parameter has parentheses. In the body of the procedure, use the parameter as you would an array. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<script runat="server">
    Function GenerateTimeWorked() As Double()
        Dim days = New Double() {9.0, 8.5, 10.5, 8.0, 7.5, 0.00, 0.00}

        Return days
    End Function

    Sub Display(ByVal summary() As Double)
        For Each day As Double In summary
            Response.Write(FormatNumber(day) & "<br>")
        Next day
    End Sub
</script>
<title>Exercise</title>
</head>
<body>
<%
    Dim work = GenerateTimeWorked()
    Display(work)
%>
</body>
</html>

Passing a Varied Number of Parameters

The Visual Basic language provides a mechanism to pass a different number of arguments every time a procedure or function is called. This is done by passing the parameter with a keyword named ParamArray that is followed by the name of the parameter and its parentheses. In the body of the procedure, treat the parameter as a normal array. Here is an example:

<script runat="server">
Sub Display(ByVal ParamArray summary() As Double)
    For Each day As Double In summary
        Response.Write(FormatNumber(day) & "<br>")
    Next day
End Sub
</script>

When calling the procedure, pass the desired number of arguments. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<script runat="server">
    Sub Display(ByVal ParamArray summary() As Double)
        For Each day As Double In summary
            Response.Write(FormatNumber(day) & "<br>")
        Next day
    End Sub
</script>
<title>Exercise</title>
</head>
<body>
<%
    Response.Write("Weekend Work<br>")
    Display(8.0, 9.0, 7.0)

    Response.Write("Whole Week Work<br>")
    Display(10.5, 9.0, 8.5, 8.0, 9.5, 7.0, 9.0, 6.5)

    Response.Write("Week Days Work<br>")
    Display(8.0, 8.0, 8.0, 8.0, 8.0)
%>
</body>
</html>

This would produce:

Passing a Varied Number of Parameters

If the function is taking more than one parameter and one of them must be a ParamArray type, this type must be the last in the parameter list.

Arrays and Classes

An Array of Objects

An array can be made of elements that are each a composite type. That is, each element can be of an object of a class type. Of course, you must have a class first. You can use one of the many built-in classes of the .NET Framework or you can create your own class. You can create an array of objects without specifying its values, using the same formula of our introduction. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class EarthLayer
    Public Sub New(ByVal layer As String,
                   ByVal width As String,
                   ByVal chemicals As String,
                   ByVal ratio As String)
        layer = layer
        Thickness = width
        Composition = chemicals
        MassRatio = ratio
    End Sub

    Public Layer As String
    Public Thickness As String
    Public Composition As String
    Public MassRatio As String
End Class
</script>
<title>Earth Composition</title>
</head>
<body>
<%
    Dim layers(4) As EarthLayer
%>
</body>
</html>

You have many options to initialize the array. You can access each object by its index and initialize it using the New operator applied to the class. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class EarthLayer
    Public Sub New(ByVal layer As String,
                              ByVal width As String,
                              ByVal chemicals As String,
                              ByVal ratio As String)
        layer = layer
        Thickness = width
        Composition = chemicals
        MassRatio = ratio
    End Sub

    Public Layer As String
    Public Thickness As String
    Public Composition As String
    Public MassRatio As String
End Class
</script>
<title>Earth Composition</title>
</head>
<body>
<%
    Dim layers(4) As EarthLayer

    layers(0) = New EarthLayer("Crust", "3-25 Miles", "Calcium (Ca), Sodium(Na)", "0.0473%")
    layers(1) = New EarthLayer("Mantle", "1800 Miles", "Iron (Fe), Magnesium (Mg), Aluminium (Al), Silicon (Si), Oxygen(O)", "67.3%")
    layers(2) = New EarthLayer("Outer Core", "1400 Miles", "Iron (Fe), Sulfur (S), Oxygen (O)", "30.8%")
    layers(3) = New EarthLayer("Inner Core", "800 Miles", "Iron (Fe)", "1.7")
%>
</body>
</html>

In the same way, you can access an object by its index and get to the members of the class using the period operator. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class EarthLayer
    Public Sub New(ByVal layer As String,
                   ByVal width As String,
                   ByVal chemicals As String,
                   ByVal ratio As String)
        Me.Layer = layer
        Me.Thickness = width
        Me.Composition = chemicals
        Me.MassRatio = ratio
    End Sub

    Public Layer As String
    Public Thickness As String
    Public Composition As String
    Public MassRatio As String
End Class
</script>
<title>Earth Composition</title>
</head>
<body>
<%
    Dim i As Integer
    Dim layer As EarthLayer
    Dim layers(4) As EarthLayer

    layers(0) = New EarthLayer("Crust", "3-25 Miles", "Calcium (Ca), Sodium(Na)", "0.0473%")
    layers(1) = New EarthLayer("Mantle", "1800 Miles", "Iron (Fe), Magnesium (Mg), Aluminium (Al), Silicon (Si), Oxygen(O)", "67.3%")
    layers(2) = New EarthLayer("Outer Core", "1400 Miles", "Iron (Fe), Sulfur (S), Oxygen (O)", "30.8%")
    layers(3) = New EarthLayer("Inner Core", "800 Miles", "Iron (Fe)", "1.7")

    Response.Write("<table border=3><tr><td><b>Layer</b></td><td><b>Thickness</b></td><td><b>Composition</b></td><td><b>Mass Ratio</b></td></tr>")
    For i = 0 To 3
        layer = layers(i)

        Response.Write("<tr><td>" & layer.Layer & "</td><td>" & layer.Thickness & "</td><td>" & layer.Composition & "</td><td>" & layer.MassRatio & "</td></tr>")
    Next
    Response.Write("</table>")
%>
</body>
</html>

This would produce:

An Array of Objects

Another way to initialize the array is to create each object in some curly brackets applied to the variable, as seen for primitive types. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class EarthLayer
    Public Sub New(ByVal layer As String,
                           ByVal width As String,
                           ByVal chemicals As String,
                           ByVal ratio As String)
        Me.Layer = layer
        Me.Thickness = width
        Me.Composition = chemicals
        Me.MassRatio = ratio
    End Sub

    Public Layer As String
    Public Thickness As String
    Public Composition As String
    Public MassRatio As String
End Class
</script>
<title>Earth Composition</title>
</head>
<body>
<%
    Dim i As Integer
    Dim layer As EarthLayer
    Dim layers = New EarthLayer() {
        New EarthLayer("Crust", "3-25 Miles", "Calcium (Ca), Sodium(Na)", "0.0473%"),
        New EarthLayer("Mantle", "1800 Miles", "Iron (Fe), Magnesium (Mg), Aluminium (Al), Silicon (Si), Oxygen(O)", "67.3%"),
        New EarthLayer("Outer Core", "1400 Miles", "Iron (Fe), Sulfur (S), Oxygen (O)", "30.8%"),
        New EarthLayer("Inner Core", "800 Miles", "Iron (Fe)", "1.7") }

    Response.Write("<table border=3><tr><td><b>Layer</b></td><td><b>Thickness</b></td><td><b>Composition</b></td><td><b>Mass Ratio</b></td></tr>")
    For i = 0 To 3
        layer = layers(i)

        Response.Write("<tr><td>" & layer.Layer & "</td><td>" & layer.Thickness & "</td><td>" & layer.Composition & "</td><td>" & layer.MassRatio & "</td></tr>")
    Next
    Response.Write("</table>")
%>
</body>
</html>

Returning an Array of Objects From a Function

You can create a function that returns an array of objects. The concept is the same applied as for primitive types.Here is an example:

<script Language="VB" runat="server">
    Public Structure USState
        Public Name As String
        Public Abbreviation As String
        Public AreaSqrKm As Integer
        Public AreaSqrMi As Integer
        Public AdmissionToUnionYear As Integer
        Public AdmissionToUnionOrder As Integer
        Public Capital As String
    End Structure

    Function CreateStates() As USState()
        Dim states = New USState() {
            New USState With {.Name = "Alabama", .Abbreviation = "AL", .AreaSqrKm = 135775, .AreaSqrMi = 52423, .AdmissionToUnionYear = 1819, .AdmissionToUnionOrder = 22, .Capital = "Montgomery"},
            New USState With {.Name = "Alaska", .AreaSqrKm = 1700139, .AreaSqrMi = 656424, .AdmissionToUnionYear = 1959, .AdmissionToUnionOrder = 49, .Capital = "Juneau", .Abbreviation = "AK"},
            New USState With {.Name = "Arizona", .Abbreviation = "AZ", .AreaSqrKm = 295276, .AreaSqrMi = 114006, .AdmissionToUnionYear = 1912, .AdmissionToUnionOrder = 48, .Capital = "Phoenix"},
            New USState With {.Name = "Arkansas", .Abbreviation = "AR", .AreaSqrKm = 137742, .AreaSqrMi = 53182, .AdmissionToUnionYear = 1836, .AdmissionToUnionOrder = 25, .Capital = "Little Rock"},
            New USState With {.Name = "California", .Abbreviation = "CA", .AreaSqrKm = 424002, .AreaSqrMi = 163707, .AdmissionToUnionYear = 1850, .AdmissionToUnionOrder = 31, .Capital = "Sacramento"},
            New USState With {.Name = "Colorado", .Abbreviation = "CO", .AreaSqrKm = 269620, .AreaSqrMi = 104100, .AdmissionToUnionYear = 1876, .AdmissionToUnionOrder = 38, .Capital = "Denver"}
        }

        Return states
    End Function
</script>

Passing An Array of Objects to a Function

You can create a procedure or function that takes an array of objects. In the body of the procedure, use the array normally. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script Language="VB" runat="server">
Public Structure USState
    Public Name As String
    Public Abbreviation As String
    Public AreaSqrKm As Integer
    Public AreaSqrMi As Integer
    Public AdmissionToUnionYear As Integer
    Public AdmissionToUnionOrder As Integer
    Public Capital As String
End Structure

Function CreateStates() As USState()
    Dim states = New USState() {
        New USState With {.Name = "Alabama", .Abbreviation = "AL", .AreaSqrKm = 135775, .AreaSqrMi = 52423, .AdmissionToUnionYear = 1819, .AdmissionToUnionOrder = 22, .Capital = "Montgomery"},
        New USState With {.Name = "Alaska", .AreaSqrKm = 1700139, .AreaSqrMi = 656424, .AdmissionToUnionYear = 1959, .AdmissionToUnionOrder = 49, .Capital = "Juneau", .Abbreviation = "AK"},
        New USState With {.Name = "Arizona", .Abbreviation = "AZ", .AreaSqrKm = 295276, .AreaSqrMi = 114006, .AdmissionToUnionYear = 1912, .AdmissionToUnionOrder = 48, .Capital = "Phoenix"},
        New USState With {.Name = "Arkansas", .Abbreviation = "AR", .AreaSqrKm = 137742, .AreaSqrMi = 53182, .AdmissionToUnionYear = 1836, .AdmissionToUnionOrder = 25, .Capital = "Little Rock"},
        New USState With {.Name = "California", .Abbreviation = "CA", .AreaSqrKm = 424002, .AreaSqrMi = 163707, .AdmissionToUnionYear = 1850, .AdmissionToUnionOrder = 31, .Capital = "Sacramento"},
        New USState With {.Name = "Colorado", .Abbreviation = "CO", .AreaSqrKm = 269620, .AreaSqrMi = 104100, .AdmissionToUnionYear = 1876, .AdmissionToUnionOrder = 38, .Capital = "Denver"}
    }

    Return states
End Function

Public Sub Show(ByVal statistics As USState())
    Dim state As USState

    Response.Write("<table border=4><tr><td><b>Name</b></td><td><b>Abbreviation</b></td><td><b>Area(Sqr Km)</b></td><td><b>Area(Sqr Mi)</b></td><td><b>Year of Admission to Union</b></td><td><b>Order of Admission to Union</b></td><td><b>Capital</b></td></tr>")
    For Each state In statistics
        Response.Write("<tr><td>" & state.Name & "</td><td>" & state.Abbreviation & "</td><td>" & state.AreaSqrKm & "</td><td>" & state.AreaSqrMi & "</td><td>" & state.AdmissionToUnionYear & "</td><td>" & state.AdmissionToUnionOrder & "</td><td>" & state.Capital & "</td></tr>")
    Next
    Response.Write("</table>")
End Sub
</script>
<title>States Statistics</title>
</head>
<body>
<%
    Dim states = CreateStates()
    Show(states)
%>
</body>
</html>

This would produce:

Passing An Array of Objects

A Field of a Class as an Array

You can create a class member that is an array. It is created and used like an array variable.

A Property as an Array

A property can be an array type. When specifying the data type of the property, make sure it is followed by parentheses. Here is an example:

<script runat="server">
Public Class MetroStation
    Public Sub New(ByVal number As Integer,
                   ByVal name As String,
                   ByVal longTermParting As Boolean,
                   ByVal shortTermParting As Boolean)
        Me.StationNumber = number
        Me.StationName = name
        Me.DailyParking = longTermParting
        Me.MeteredParking = shortTermParting
    End Sub

    Public Property StationNumber As Integer
    Public Property StationName As String
    Public Property Line As String
    Public Property DailyParking As Boolean
    Public Property MeteredParking As Boolean
End Class

Public Class MetroLine
    Public Property Line As String
    Public Property Stations As MetroStation()
End Class
</script>

If the property is not self implemented, make it returns an array or one is assigned to it. You can do this in a constructor or in an event that would be fired before any other event that would use the array. This type of initialization is usually done in a Load event of a form. After initializing the array, you can then access in another method or another event of the form. Here is an example:

<script runat="server">
Public Class MetroStation
    Public Sub New(ByVal number As Integer,
                   ByVal name As String,
                   ByVal longTermParting As Boolean,
                   ByVal shortTermParting As Boolean)
        Me.StationNumber = number
        Me.StationName = name
        Me.DailyParking = longTermParting
        Me.MeteredParking = shortTermParting
    End Sub

    Public Property StationNumber As Integer
    Public Property StationName As String
    Public Property Line As String
    Public Property DailyParking As Boolean
    Public Property MeteredParking As Boolean
End Class

Public Class MetroLine
    Private places As MetroStation()

    Public Property Line As String
    Public Property Stations As MetroStation()
        Get
            Return places
        End Get
        Set(value As MetroStation())
            places = value
        End Set
    End Property
End Class
</script>

You can then use the property like a regular array. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class MetroStation
    Public Sub New(ByVal number As Integer,
                   ByVal name As String,
                   ByVal longTermParting As Boolean,
                   ByVal shortTermParting As Boolean)
        Me.StationNumber = number
        Me.StationName = name
        Me.DailyParking = longTermParting
        Me.MeteredParking = shortTermParting
    End Sub

    Public Property StationNumber As Integer
    Public Property StationName As String
    Public Property Line As String
    Public Property DailyParking As Boolean
    Public Property MeteredParking As Boolean
End Class

Public Class MetroLine
    Private places As MetroStation()

    Public Property Line As String
    Public Property Stations As MetroStation()
        Get
            Return places
        End Get
        Set(value As MetroStation())
            places = value
        End Set
    End Property
End Class
</script>
<title>Metro System - Orange Line</title>
</head>
<body>
<h3>Metro System - Orange Line</h3>
<%
    Dim line As MetroLine
    Dim station As MetroStation

    line = New MetroLine
    line.Line = "Orange"
    line.Stations = New MetroStation() {
            New MetroStation(7940, "Vienna/Fairfax-GMU", True, True),
            New MetroStation(9571, "Dunn Loring-Merrifield", True, True),
            New MetroStation(9508, "West Falls Church-VT/UVA", True, True),
            New MetroStation(7171, "Ballston-MU", False, False),
            New MetroStation(9205, "Virginia Square-GMU", False, False),
            New MetroStation(3947, "Clarendon", False, False),
            New MetroStation(2036, "Court House", False, False),
            New MetroStation(1739, "Rosslyn", False, False),
            New MetroStation(9284, "Foggy Bottom-GWU", False, False),
            New MetroStation(9527, "Farragut West", False, False),
            New MetroStation(9294, "Metro Center", False, False),
            New MetroStation(3028, "Federal Triangle", False, False)
    }

    Response.Write("<table border=1><tr><td>Station #</td><td>Station Name</td><td>Line</td><td>Daily Parking?</td><td>Metered Parking?</td></tr>")
    For i = 0 To line.Stations.Length - 1
        station = line.Stations(i)

        Response.Write("<tr><td>" & station.StationNumber & "</td><td>" & station.StationName & "</td><td>" & line.Line & "</td><td>" & station.DailyParking & "</td><td>" & station.MeteredParking & "</td></tr>")
    Next
    Response.Write("</table>")
%>
</body>
</html>

This would produce:

Passing An Array of Objects

Passing an Array to a Method

You can pass an array to a method or a constructor of a class. In the method or constructor, use the array like any other. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class MetroStation
    Public Sub New(ByVal number As Integer,
                   ByVal name As String,
                   ByVal longTermParting As Boolean,
                   ByVal shortTermParting As Boolean)
        Me.StationNumber = number
        Me.StationName = name
        Me.DailyParking = longTermParting
        Me.MeteredParking = shortTermParting
    End Sub

    Public Property StationNumber As Integer
    Public Property StationName As String
    Public Property Line As String
    Public Property DailyParking As Boolean
    Public Property MeteredParking As Boolean
End Class

Public Class MetroLine
    Private places As MetroStation()

    Public Sub New(ByVal color As String, ByVal stations As MetroStation())
        Me.Line = color
        Me.places = stations
    End Sub

    Public Property Line As String

    Public Property Stations As MetroStation()
        Get
            Return places
        End Get
        Set(value As MetroStation())
            places = value
        End Set
    End Property
End Class
</script>
<title>Metro System - Red Line</title>
</head>
<body>
<h3>Metro System - Red Line</h3>
<%
    Dim line As MetroLine
    Dim station As MetroStation

    Dim redLine = New MetroStation() {
        New MetroStation(2014, "Shady Grove", True, True),
        New MetroStation(1660, "Rockville", True, True),
        New MetroStation(9722, "Twinbrook", True, True),
        New MetroStation(2048, "White Flint", True, True),
        New MetroStation(8294, "Grosvenor-Strathmore", True, True),
        New MetroStation(2864, "Medical Center", False, False),
        New MetroStation(2814, "Bethesda", False, False),
        New MetroStation(9204, "Friendship Heights", False, False),
        New MetroStation(8648, "Tenleytown-AU", False, True),
        New MetroStation(2522, "Van Ness - UDC", False, False),
        New MetroStation(9741, "Cleveland Park", False, False),
        New MetroStation(1626, "Woodley Park-Zoo/Adams Morgan", False, False),
        New MetroStation(9279, "Dupont Circle", False, False),
        New MetroStation(7974, "Farragut North", False, False),
        New MetroStation(9294, "Metro Center", False, False),
        New MetroStation(1359, "Gallery Pl - Chinatown", False, False),
        New MetroStation(8200, "Judiciary Square", False, False),
        New MetroStation(1802, "Union Station", False, False),
        New MetroStation(2014, "NoMa-Gallaudet U", False, False),
        New MetroStation(1116, "Rhode Island Ave-Brentwood", True, True),
        New MetroStation(3948, "Brookland-CUA", False, True),
        New MetroStation(9794, "Fort Totten", True, True),
        New MetroStation(8270, "Takoma", False, True),
        New MetroStation(9274, "Silver Spring", False, False),
        New MetroStation(1417, "Forest Glen", True, True),
        New MetroStation(9737, "Wheaton", True, False),
        New MetroStation(8802, "Glenmont", True, True)}

    line = New MetroLine("Red", redLine)

    Response.Write("<table border=5><tr><td>Station #</td><td>Station Name</td><td>Line</td><td>Daily Parking?</td><td>Metered Parking?</td></tr>")
    For i = 0 To line.Stations.Length - 1
        station = line.Stations(i)

        Response.Write("<tr><td>" & station.StationNumber & "</td><td>" & station.StationName & "</td><td>" & line.Line & "</td><td>" & station.DailyParking & "</td><td>" & station.MeteredParking & "</td></tr>")
    Next
    Response.Write("</table>")
%>
</body>
</html>

This would produce:

Passing an Array to a Method

Returning an Array From a Method

You can create a method that returns an array of objects. The rules are exactly the same as an array of objects returned from a function. Here are examples:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Class MetroStation
    Public Sub New(ByVal number As Integer,
                   ByVal name As String,
                   ByVal longTermParting As Boolean,
                   ByVal shortTermParting As Boolean)
        Me.StationNumber = number
        Me.StationName = name
        Me.DailyParking = longTermParting
        Me.MeteredParking = shortTermParting
    End Sub

    Public Property StationNumber As Integer
    Public Property StationName As String
    Public Property Line As String
    Public Property DailyParking As Boolean
    Public Property MeteredParking As Boolean
End Class

Public Class MetroLine
    Public Sub New(ByVal color As String)
        Line = color
    End Sub

    Public Property Line As String
    Public Property Stations As MetroStation()

    Function CreateRedLineStations() As MetroStation()
        Return New MetroStation() {
            New MetroStation(2014, "Shady Grove", True, True),
            New MetroStation(1660, "Rockville", True, True),
            New MetroStation(9722, "Twinbrook", True, True),
            New MetroStation(2048, "White Flint", True, True),
            New MetroStation(8294, "Grosvenor-Strathmore", True, True),
            New MetroStation(2864, "Medical Center", False, False),
            New MetroStation(2814, "Bethesda", False, False),
            New MetroStation(9204, "Friendship Heights", False, False),
            New MetroStation(8648, "Tenleytown-AU", False, True),
            New MetroStation(2522, "Van Ness - UDC", False, False),
            New MetroStation(9741, "Cleveland Park", False, False),
            New MetroStation(1626, "Woodley Park-Zoo/Adams Morgan", False, False),
            New MetroStation(9279, "Dupont Circle", False, False),
            New MetroStation(7974, "Farragut North", False, False),
            New MetroStation(9294, "Metro Center", False, False),
            New MetroStation(1359, "Gallery Pl - Chinatown", False, False),
            New MetroStation(8200, "Judiciary Square", False, False),
            New MetroStation(1802, "Union Station", False, False),
            New MetroStation(2014, "NoMa-Gallaudet U", False, False),
            New MetroStation(1116, "Rhode Island Ave-Brentwood", True, True),
            New MetroStation(3948, "Brookland-CUA", False, True),
            New MetroStation(9794, "Fort Totten", True, True),
            New MetroStation(8270, "Takoma", False, True),
            New MetroStation(9274, "Silver Spring", False, False),
            New MetroStation(1417, "Forest Glen", True, True),
            New MetroStation(9737, "Wheaton", True, False),
            New MetroStation(8802, "Glenmont", True, True)}
    End Function

    Function CreateGreenLineStations() As MetroStation()
        Return New MetroStation() {
            New MetroStation(1862, "Greenbelt", True, True),
            New MetroStation(3940, "College Park-U of MD", True, False),
            New MetroStation(9283, "Prince George's Plaza", True, True),
            New MetroStation(7304, "West Hyattsville", True, True),
            New MetroStation(9794, "Fort Totten", True, True),
            New MetroStation(5938, "Georgia Ave-Petworth", False, False),
            New MetroStation(2924, "Columbia Heights", False, False),
            New MetroStation(9273, "U Street/African-Amer Civil War Memorial/Cardozo", False, False),
            New MetroStation(3948, "Shaw-Howard U", False, False),
            New MetroStation(8604, "Mt Vernon Sq 7th St-Convention Center", False, False),
            New MetroStation(1359, "Gallery Pl - Chinatown", False, False),
            New MetroStation(9283, "Archives-Navy Memorial-Penn Quarter", False, False),
            New MetroStation(9318, "L'Enfant Plaza", False, False),
            New MetroStation(9297, "Waterfront", False, False),
            New MetroStation(4118, "Navy Yard-Ballpark", False, False),
            New MetroStation(4835, "Anacostia", True, True),
            New MetroStation(4738, "Congress Heights", False, True)}
    End Function

    Public Function CreateOrangeLineStations() As MetroStation()
        Return New MetroStation() {
            New MetroStation(7940, "Vienna/Fairfax-GMU", True, True),
            New MetroStation(9571, "Dunn Loring-Merrifield", True, True),
            New MetroStation(9508, "West Falls Church-VT/UVA", True, True),
            New MetroStation(7171, "Ballston-MU", False, False),
            New MetroStation(9205, "Virginia Square-GMU", False, False),
            New MetroStation(3947, "Clarendon", False, False),
            New MetroStation(2036, "Court House", False, False),
            New MetroStation(1739, "Rosslyn", False, False),
            New MetroStation(9284, "Foggy Bottom-GWU", False, False),
            New MetroStation(9527, "Farragut West", False, False),
            New MetroStation(9294, "Metro Center", False, False),
            New MetroStation(3028, "Federal Triangle", False, False)}
    End Function

    Public Function CreateYellowLineStations() As MetroStation()
        Return New MetroStation() {
            New MetroStation(9794, "Fort Totten", True, True),
            New MetroStation(5938, "Georgia Ave-Petworth", False, False),
            New MetroStation(2924, "Columbia Heights", False, False),
            New MetroStation(9273, "U Street/African-Amer Civil War Memorial/Cardozo", False, False),
            New MetroStation(3948, "Shaw-Howard U", False, False),
            New MetroStation(8604, "Mt Vernon Sq 7th St-Convention Center", False, False),
            New MetroStation(1359, "Gallery Pl - Chinatown", False, False),
            New MetroStation(9283, "Archives-Navy Memorial-Penn Quarter", False, False),
            New MetroStation(9318, "L'Enfant Plaza", False, False),
            New MetroStation(3640, "Pentagon", False, False),
            New MetroStation(8273, "Pentagon City", False, False),
            New MetroStation(3724, "Crystal City", False, False)}
    End Function
End Class

Sub Display(ByVal liner As MetroLine)
    Dim trains(30) As MetroStation

    Select Case liner.Line
        Case "Red"
            trains = liner.CreateRedLineStations()
        Case "Green"
            trains = liner.CreateGreenLineStations()
        Case "Orange"
            trains = liner.CreateOrangeLineStations()
        Case "Yellow"
            trains = liner.CreateYellowLineStations()
    End Select

    Response.Write("<table border=6><tr><td>Station #</td><td>Station Name</td><td>Line</td><td>Daily Parking?</td><td>Metered Parking?</td></tr>")
    For i = 0 To trains.Length - 1
        Response.Write("<tr><td>" & trains(i).StationNumber & "</td><td>" & trains(i).StationName & "</td><td>" & liner.Line & "</td><td>" & trains(i).DailyParking & "</td><td>" & trains(i).MeteredParking & "</td></tr>")
    Next
    Response.Write("</table>")
End Sub
</script>
<title>Metro System - Orange Line</title>
</head>
<body>
<%
    Dim line As New MetroLine("Yellow")

    Response.Write("<h3>Metro System - " & line.Line & " Line</h3>")

    Display(line)
%>
</body>
</html>

This would produce:

Passing An Array of Objects

Operations on an Array

Introduction

Because an array is primarily a series of objects or values, there are various pieces of information you would get interested from it. Typical operations include:

Although you can write your own routines to perform these operations, the Array class provides the methods you would need to get the necessary information.

Adding an Element to an Array

We have seen that, using the () operator, you can add a new element to an array. Still, to support this operation, the Array class is equipped with the SetValue() method that is overloaded with various versions. Here is an example that adds an element to the third position of the array:

Public Class Exercise
    Dim People(7) As Person

    Private Sub ArrayInitializer() 

        For i As Integer = 0 To 7
            People(i) = New Person
            People(i).PersonID = 0
            People(i).FirstName = ""
            People(i).LastName = ""
            People(i).Gender = "Unknown"
        Next

    End Sub

    Private Sub ShowPeople()
        lvwPeople.Items.Clear()

        For Each Pers As Person In People
            Dim lviPerson As ListViewItem = New ListViewItem(Pers.FirstName)

            lviPerson.SubItems.Add(Pers.LastName)
            lviPerson.SubItems.Add(Pers.Gender)

            lvwPeople.Items.Add(lviPerson)
        Next
    End Sub

    Private Sub Exercise_Load(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) Handles MyBase.Load
        ArrayInitializer()
        ShowPeople()
    End Sub

    Private Sub btnAdd_Click(ByVal sender As Object, _
                             ByVal e As System.EventArgs) Handles btnAdd.Click
        Dim pers As Person = New Person

        pers.PersonID = CInt(txtPersonID.Text)
        pers.FirstName = txtFirstName.Text
        pers.LastName = txtLastName.Text
        pers.Gender = cbxGenders.Text

        People.SetValue(pers, 2)
        ShowPeople()
    End Sub
End Class

When the Array.SetValue() method is called, it replaces the element at the indicated position.

Getting an Element From an Array

The reverse of adding an item to an array is to retrieve one. To support this operation, the Array class is equipped with the GetValue() method that comes in various versions. Here is an example of calling it:

Public Class Exercise
    Dim People(7) As Person

    Private Sub Exercise_Load(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) Handles MyBase.Load
        People(0) = New Person(72947, "Paulette", _
                               "Cranston", "Female")
        People(1) = New Person(70854, "Harry", _
                               "Kumar", "Male")
        People(2) = New Person(27947, "Jules", _
                               "Davidson", "Male")
        People(3) = New Person(62835, "Leslie", _
                               "Harrington", "Unknown")
        People(4) = New Person(92958, "Ernest", _
                              "Colson", "Male")
        People(5) = New Person(91749, "Patricia", _
                              "Katts", "Female")
        People(6) = New Person(29749, "Patrice", _
                              "Abanda", "Unknown")
        People(7) = New Person(24739, "Frank", _
                              "Thomasson", "Male")

        For i As Integer = 0 To People.Length - 1
            Dim lviPerson As ListViewItem = New ListViewItem(People(i).FirstName)

            lviPerson.SubItems.Add(People(i).LastName)
            lviPerson.SubItems.Add(People(i).Gender)

            lvwPeople.Items.Add(lviPerson)
        Next
    End Sub

    Private Sub lvwPeople_ItemSelectionChanged(ByVal sender As Object, _
       ByVal e As System.Windows.Forms.ListViewItemSelectionChangedEventArgs) _
                                               Handles lvwPeople.ItemSelectionChanged
        Dim pers As Person = CType(People.GetValue(e.ItemIndex), Person)

        txtPersonID.Text = pers.PersonID
        txtFirstName.Text = pers.FirstName
        txtLastName.Text = pers.LastName
        cbxGenders.Text = pers.Gender
    End Sub

End Class

When calling this method, make sure you provide a valid index, if you do not, you would get an IndexOutOfRangeException exception.

Checking the Existence of an Element

Once some elements have been added to an array, you can try to locate one. One of the most fundamental means of looking for an item consists of finding out whether a certain element exists in the array. To support this operation, the Array class is equipped with the Exists() method whose syntax is:

Public Shared Function Exists(Of T) ( _
	array As T(), _
	match As Predicate(Of T) _
) As Boolean

This is a generic method that takes two arguments. The first is the array on which you will look for the item. The second argument is a delegate that specifies the criterion to apply. Here is an example:

Public Class Exercise
    Dim People(7) As Person
    Shared IDToFind As Integer

    Private Sub Exercise_Load(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) Handles MyBase.Load
        . . . No Change
    End Sub

    Private Shared Function IDExists(ByVal p As Person) As Boolean
        If p.PersonID = IDToFind Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub btnExists_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnExists.Click
        IDToFind = CInt(txtPersonID.Text)

        If Array.Exists(People, AddressOf IDExists) Then
            MessageBox.Show("The person was found")
        Else
            MessageBox.Show("The person was not found anywhere")
        End If
    End Sub
End Class

Finding an Element

One of the most valuable operations you can perform on an array consists of looking for a particular element. To assist you with this, the Array class is equipped with the Find() method. Its syntax is:

Public Shared Function Find(Of T) ( _
	array As T(), _
	match As Predicate(Of T) _
) As T

This generic method takes two arguments. The first argument is the name of the array that holds the elements. The second argument is a delegate that has the criterion to be used to find the element. Here is an example:

Private Sub btnFind_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) Handles btnFind.Click
        IDToFind = CInt(txtPersonID.Text)

        Dim pers As Person = Array.Find(People, AddressOf IDExists)

        If Not pers Is Nothing Then
            txtFirstName.Text = pers.FirstName
            txtLastName.Text = pers.LastName
            cbxGenders.Text = pers.Gender
        End If
End Sub

Previous Copyright © 2008-2016, FunctionX Next