Lesson 8 - Arrays in VB.NET
Lesson highlights
Are you looking for a quick reference on arrays in VB.NET instead of a thorough-full lesson? Here it is:
Shortened initialization of an array:
Dim numbers() = {2, 3, 5, 7}
Writing 1
at the position (0)
:
numbers(0) = 1
Reading the value (now 1
) at the position
(0)
:
{VBNET_CONSOLE}
Dim numbers() = {2, 3, 5, 7}
numbers(0) = 1
Console.WriteLine(numbers(0))
{/VBNET_CONSOLE}
Printing the whole array:
{VBNET_CONSOLE}
Dim numbers() = {2, 3, 5, 7}
numbers(0) = 1
For Each i As Integer In numbers
Console.Write("{0} ", i)
Next
{/VBNET_CONSOLE}
Creating and empty array and generating the
values using a For
loop:
{VBNET_CONSOLE}
Dim numbers(9) As Integer
For i As Integer = 0 To numbers.Length - 1
numbers(i) = i + 1
Next
For Each i as Integer In numbers
Console.Write("{0} ", i)
Next
Console.ReadKey()
{/VBNET_CONSOLE}
Sorting/searching using the
Array
class:
{VBNET_CONSOLE}
Dim simpsons() = {"Homer", "Marge", "Bart", "Lisa", "Maggie"}
Array.Sort(simpsons) ' sort the array
Array.Reverse(simpsons) ' reverse the item order
Console.WriteLine("Bart is at the position: {0}", Array.IndexOf(simpsons, "Bart")) ' gets the item index
Dim copy(4) As String
Array.Copy(simpsons, copy, 5) ' copies 5 items to the "copy" array
For Each s As String In simpsons
Console.Write("{0} ", s)
Next
Console.ReadKey()
{/VBNET_CONSOLE}
Calling instance methods (min/max/average/sum/reverse/more):
Dim numbers() = {2, 3, 3, 5, 7} Console.WriteLine("Min: {0}", numbers.Min()) Console.WriteLine("Max: {0}", numbers.Max()) Console.WriteLine("Average: {0}", numbers.Average()) Console.WriteLine("Sum: {0}", numbers.Sum()) Console.WriteLine("First: {0}", numbers.First()) Console.WriteLine("Last: {0}", numbers.Last()) Console.WriteLine("Contains value 2: {0}", numbers.Contains(2)) Console.WriteLine("Reversed: {0}", String.Join(" ", numbers.Reverse())) Console.WriteLine("Distinct: {0}", String.Join(" ", numbers.Distinct())) Console.ReadKey() ' Even more array methods can be found used in the lesson below
Would you like to learn more? A complete lesson on this topic follows.
In the previous tutorial, Sanitizing user input in VB.NET, we sanitized the user input parts of our calculator in Visual Basic .NET. In today's lesson, we're going to introduce you all to the array data structure and show you what it's capable of accomplishing.
Array
Imagine that you want to store some information about multiple items, e.g.
you want to keep 10 numbers in memory, each of the fields of a checkerboard or
names of 50 users. Perhaps you realize that there must be an easier way than to
start typing variables like user1
, user2
... up until user50
. Despite the fact that there may be 1000
of them. How would go about searching for something in there? Definitely not
like that!
If we need to store a larger amount of variables of the same
type, we can solve this problem using an array. We can imagine it as a
row of boxes, each of them containing one item. The boxes are numbered by
indexes, the first one has index 0
.
(We see an array of 8 numbers on this picture)
Programming languages are very different in the way they work with arrays. In some languages (especially the older ones, compiled), it wasn't possible to create an array with a size specified at runtime (e.g. to specify its size using some variable). Arrays had to be declared with a constant size in the source code. A workaround was made by inventing pointers and custom data structures, which often lead to errors in manual memory management and to program instability (e.g. in C++). On the other hand, some interpreted languages allow us to not only declare arrays of any size but to also change the size of an existing array (it's possible e.g. in PHP). We know that VB.NET is a virtual machine, which is something between a compiled language and an interpreted language. Therefore, we are able to declare an array with a size which we can enter during the runtime, but once an array is created, its size can't be modified. Of course, we can work around it or use other data structures, but we'll get to that later.
You might be wondering why we're dealing with arrays when they evidently have some limitations and there are better data structures out there. The answer is: "Arrays are simple". I don't mean that they're easy for us to understand, which they are, but it's simple for Visual Basic. Working with arrays is fast since the items are simply stored in memory as a sequence (next to each other), and every item occupies the same amount of space and is quickly accessible. Many internal .NET functions work with arrays somehow or return them. It is a key data structure.
We use loops for the mass handling of array items.
We declare an array using parentheses:
Dim numbers(9) As Integer
Numbers
is obviously a name of our variable. We've just declared
that the variable numbers
is an array of Integer
s. It
will be initialized automatically if we specify the number
of
items. Now we have an array of a size of ten Integer
s in the
variable numbers
. Beware that we specify the length as the
last index, so numbers(9)
have 10
items.
The array items can be accessed through parentheses. Let's store the number 1
in the first index (index 0
):
Dim numbers(9) As Integer numbers(0) = 1
Filling arrays manually like this wouldn't be too effective. Let's use a loop
and fill an array with numbers from 1
to 10
. We'll use
a for
loop to do just that:
Dim numbers(9) As Integer numbers(0) = 1 For i As Integer = 0 To 9 numbers(i) = i + 1 Next
If we want to print this array, we need to add this piece of code after the one above:
{VBNET_CONSOLE}
Dim numbers(9) As Integer
numbers(0) = 1
For i As Integer = 0 To 9
numbers(i) = i + 1
Next
For i As Integer = 0 To numbers.Length - 1
Console.Write("{0} ", numbers(i))
Next
{/VBNET_CONSOLE}
Note that the array provides the Length
property, where its
length is stored, which is the number of its items.
Console application
1 2 3 4 5 6 7 8 9 10
We can also use a simplified version of the loop to work with collections,
known as For Each
. It iterates over the items in the array and
detects the length of an array by itself. Its syntax is the following:
For Each variable As datatype In collection ' commands Next
The loop iterates over the items in the collection sequentially, from the first one to the last one. "Collection" is the general term for structures that contain multiple items, which in our case is an array. The current item is stored in the variable in each iteration of the loop.
Let's rewrite our existing program and use For Each
.
For Each
does not have a control variable, so it's
not suitable for the creation of our array. We will primarily use it for
printing.
{VBNET_CONSOLE}
Dim numbers(9) As Integer
numbers(0) = 1
For i As Integer = 0 To 9
numbers(i) = i + 1
Next
For Each number As Integer In numbers
Console.Write("{0} ", number)
Next
{/VBNET_CONSOLE}
The output:
Console application
1 2 3 4 5 6 7 8 9 10
Of course, we can also fill an array manually, even without accessing each index gradually. We'll use curly brackets and separate items by commas:
Dim simpsons() = {"Homer", "Marge", "Bart", "Lisa", "Maggie"}
Notice that we didn't have to specify the number of items in this declaration.
Arrays are often used to store intermediate results, which are used later in the program. When we need some result 10 times, we won't calculate the same thing 10 times, instead, we'll calculate it once and put it into an array, then we just read the result.
The Array
class methods
.NET provides the Array
class for us which contains helpful
methods for working with arrays. Let's look at them:
Sort()
As the name suggests, the method will sort our array. Its only parameter is
the array that we want to sort. It is so clever that it works according to what
we have stored in the array. String
s are sorted alphabetically,
numbers are sorted depending on their value. Let's try to sort and print our
Simpsons family:
{VBNET_CONSOLE}
Dim simpsons() = {"Homer", "Marge", "Bart", "Lisa", "Maggie"}
Array.Sort(simpsons)
For Each s As String In simpsons
Console.Write("{0} ", s)
Next
Console.ReadKey()
{/VBNET_CONSOLE}
The output:
Console application
Bart Homer Lisa Maggie Marge
Try making an array of numbers and sort them, so you'll understand that it works for numerical datatypes as well.
Reverse()
Reverse()
is used to reverse an array (the first item will be
the last etc.). That can be used e.g. for descending sorting:
{VBNET_CONSOLE}
Dim simpsons() = {"Homer", "Marge", "Bart", "Lisa", "Maggie"}
Array.Sort(simpsons)
Array.Reverse(simpsons)
For Each s As String In simpsons
Console.Write("{0} ", s)
Next
Console.ReadKey()
{/VBNET_CONSOLE}
IndexOf()
and
LastIndexOf()
These methods return the index of the first or last occurrence of an item. If
they don't find the item, they return -1
. Each method takes two
parameters, the first is an array, the second is the item we're searching for.
Let's allow the user to enter the name of a Simpson's character and tell them at
what position he/she is stored. It won't be very useful for us now since all
we've got in our array are string
s; however, it'll be very useful
for us when adding complex objects in the array. Just keep in mind that that's a
possibility until then.
{VBNET_CONSOLE}
Dim simpsons() = {"Homer", "Marge", "Bart", "Lisa", "Maggie"}
Console.WriteLine("Hello! What is your favorite character in the Simpsons (you may only choose from the core family members): ")
Dim simpson As String = Console.ReadLine()
Dim position As Integer = Array.IndexOf(simpsons, simpson)
If position >= 0 Then
Console.WriteLine("If I had to rank them, that would be no. {0} on my list.", position + 1)
Else
Console.WriteLine("Hey! That's not a Simpson!")
End If
Console.ReadKey()
{/VBNET_CONSOLE}
Console application
Hello! What is your favorite character in the Simpsons (you may only choose from the core family members):
Homer
If I had to rank them, that would be no. 1 on my list!
Copy()
Copy()
, as the name suggests, copies a part of the array into
another array. The first parameter is the source array, the second is a target
one and the third is a number of items to be copied.
Methods on the array
The Array
class is not the only way to manipulate with arrays.
We can also call a lot of methods directly on individual array instances
(concrete variables). We'll go over a couple of them, but keep in mind that
there are a whole lot of them. We won't make examples this time
around, we'll just describe them:
Length
We've already mentioned Length
. It returns the length of an
array. It is not a method, but the property, so we don't write the parentheses
()
after it.
Min()
, Max()
,
Average()
, Sum()
Mathematical methods which return the lesser of the items
(Min()
), the largest item (Max()
), the average of all
the items (Average()
) and the sum of all the items
(Sum()
). The methods have no parameters.
Concat(), Intersect(), Union()
All these methods return a new array as the output and accept the second
array as the input. Concat()
performs a concatenation which merges
our array with the second one and returns a newly created array.
Intersect()
performs the intersection of the two arrays. It creates
an array with elements that are common in both arrays. Union()
, on
the other hand, performs a union. It works like Concat()
, but the
elements which were in both arrays are in the new array will appear only
once.
First()
and Last()
As the names suggest, these methods return the first and the last item. They don't take any parameters.
Take()
and Skip()
Both of these methods take as a parameter the number of items.
Take()
returns an array with a given number of items copied from
the beginning of the original array. Skip()
, on the contrary,
returns an array without these first items.
Contains()
The method returns True
/False
depending on whether
the item specified as a parameter is contained in the array.
Reverse()
We already know the Reverse()
method from the Array
class, but if we call it on a particular array, the items will be reversed.
Instead, a new reversed array will be created and returned. The method has no
parameters.
Distinct()
Distinct()
is a method without parameters and ensures that each
element will be in the array only once, thus it removes duplicate elements, and
returns a unique array as the return value. It doesn't modify our original
array. Many methods don't change our arrays directly, but only return a new
array, i.e. Concat()
, Intersect()
,
Union()
, Reverse()
and Distinct()
methods, in which the desired changes are made. If we want to modify the
original array, we have to assign the returned array to the original one.
Unfortunately, these methods don't return an array directly for a reason which
we'll go over later, namely, the IEnumerable
type. If we want to
store the result back into the original array, we have to convert it to an array
using the ToArray()
method.
Dim numbers() = { 1, 2, 3, 3, 3, 5 } numbers = numbers.Distinct().ToArray()
A variable length of the array
We mentioned that the length of the array can be defined during run-time, let's try it out as well as some other methods:
Console.WriteLine("Hello, I'll calculate your grade average.") Console.WriteLine("How many grades would you like to enter?") Dim count As Integer = Console.ReadLine() Dim numbers(count - 1) As Integer For i As Integer = 0 To count - 1 Console.Write("Enter grade number {0}: ", i + 1) numbers(i) = Console.ReadLine() Next Console.WriteLine("Your grade average is: {0}", numbers.Average()) Console.ReadKey()
Console application
Hello, I'll calculate your grade average.
How many grades would you like to enter?
5
Enter grade number 1: 1
Enter grade number 2: 2
Enter grade number 3: 2
Enter grade number 4: 3
Enter grade number 5: 5
Your grade average is: 2.6
This example could obviously be written without an array, but what if we wanted to compute the median, or print the given numbers backward? We wouldn't be able to do so without arrays. All of the original values are available in the array, which we can work with to do whatever we need to.
That's enough for today, you can play with arrays for a while if you'd like. In the next lesson, Solved tasks for Visual Basic .NET lessons 7-8, I've got a surprise for you I think you might like
In the following exercise, Solved tasks for Visual Basic .NET lessons 7-8, we're gonna practice our knowledge from previous lessons.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 39x (204.92 kB)
Application includes source codes in language VB.NET