The key lies in the fact that the data is related. Rather than breaking up your "car" into pieces to store in different arrays, a Class would allow you to create a Car
object, and store various cars in a typed List
:
Five Minute Intro to Classes
and Lists
Public Class Car
Public Property Id As Int32
Public Property Make As String
Public Property Model As String
Public Property Year As Int32
'... etc
End Class
Now you have a container to save all the info for one car. This is like a blueprint for what a Car
object will look like. A Class can also contain methods (Sub
or Function
) to manage the data they store so that everything relating to a Car or Employee or Order can be managed by that class.
Dim c As New Car ' create a new car object
c.Make = "Mazda"
c.Model = "Miata"
c.Year = 2013
Or initialize when you declare it:
Dim c As New Car With {.Make = "Mazda", .Model = "Miata" ...}
Now, the New Millennium version of arrays, is a List
. These are much easier to work with because they size themselves:
Dim Cars As New List(Of Car)
The Cars
collection can only store car objects, each car it stores keeps the data together for each one. There are many other collection types such as Dictionary
you will eventually want to get familiar with. Add the Mazda to the List:
' c is the car object created above
Cars.Add(c)
Unlike arrays there is no need to know how many cars you will be working with because they resize themselves. To reference one, Cars(n)
will refer to a car object:
' n is the index of a car in the list
Dim str = Cars(n).Make & " is " & Cars(n).Color
Iterate the list, using a temp Car
variable:
For Each c As Car In Cars
' c will be Cars(0), Cars(1) etc as we step thru
Console.WriteLine("Index {0} is a BEAUTIFUL {1} {2}",
Cars.IndexOf(c), c.Year, c.Model)
' e.g
' "Index 4 is a BEAUTIFUL 2015 Camry"
Next
Find one or the first of a kind:
Dim myCar = Cars.FirstOrDefault(Function (f) f.Make = "Mazda" AndAlso f.Year = 2013)
A List(Of T)
can be used as a DataSource
for some controls:
myDGV.DataSource = Cars
The DataGridView will create a column for each Property in the Car
class, and add a row for each car object in the list - simple!
Or:
myListBox.DataSource
myList.DisplayMember = "Make"
myList.ValueMember = "Id"
The user will see the Make
in the ListBox (or whatever you define). SelectedValue
will be the Id of the car object they selected and SelectedItem
will be the entire car object. No need to go rifling thru different arrays to find related data - it is always together in one spot.