Title: Chapter 11 Using Collections
1Chapter 11Using Collections
- Advanced Programming Using Visual Basic.NET
.
2Referencing Collection Items
A collection may consist of a group of
individual items or a collection of objects.
- To reference an individual table in the Tables
collection - Assuming that DsStoreSales1 is a dataset based on
an .xsd file (a strongly typed dataset)
The words collection, list, and data structure
are used interchangeably
OR
DsStoreSales1.Tables("Stores") 'The Stores table
DsStoreSales1.Tables(0) 'Also refers to the
Stores table, assuming that it is the first table
DsStoreSales1.Stores
Referencing Collection Items
3System.Collections Namespace
- The System.Collections namespace provides classes
for several different types of collections. - Some types of collections are based on the way
items are handled. - A queue is like a line the first item in should
be the first one out (FIFO)
System.Collections Namespace
4System.Collections Namespace
- In a stack collection, the last one in is the
first one out (LIFO) - A dictionary collection consists of a key and
value pair - Hashtable
- SortedList
- All of the collections inherit from the same base
System.Collections Namespace
5System.Collections Namespace
Collection Class
System.Collections Namespace
6System.Collections Namespace
Collection Class
System.Collections Namespace
Â
7Collection Classes Demo
Dim mstrLanguage As String() "English",
"Spanish", "Chinese", "Italian", "German",
"French", "Tagalog"
Dim mstrList As SortedList Dim mhshTable As
Hashtable Dim mstkList As Stack Dim mqueList As
Queue
System.Collections Namespace
Â
8Stacks
An unsorted list, like a stack is not the best
type of list for performing searches.
- An unsorted list
- LIFO
- Use the Push method to add an item to the list.
- Use the Pop method to remove an item from the
list. - Use the Peek method to look at the last item
without removing it.
'Add an item to the stack mstkList.Push(strItem)
'View the last item without removing it strItem
mstkList.Peek() Â 'Remove the last item from the
list mstkList.Pop()
Using Stacks
Â
9Using Queues
'Add an item to the queue mqueList.Enqueue(strItem
)
'View the next item to be removed without
removing it strItem mqueList.Peek() Â 'Remove
the first item from the list mqueList.Dequeue()
- An unsorted list
- LIFO
- Use the Enqueue method to add items to the queue
- Use the Dequeue method to remove items from the
queue
Using Stacks
Â
10Using Hash Tables
- A dictionary-type collection of key/value pairs
- Fastest type of list for searching
- Keys are calculated using an algorithm that
produces the same key with every calculation. - Use the GetHashCode method to calculate the key.
- Use Add and Remove methods to place/remove items
from the list.
'Calculate the hash code for the key strKey
strItem.GetHashCode.ToString 'Add an item to the
hash table mhshTable.Add(strKey,
strItem) Â 'Calculate the hash code of a selected
item strItem lstLanguages.SelectedItem.ToString
strKey strItem.GetHashCode.ToString 'Remove the
selected item by key mhshTable.Remove(strKey)
Using Stacks
Â
11Using Hash Tables
- Dont use a hash table when
- Data must be in a specific order
- When there may be duplicate keys
- Refer to the collection of items in a hash table
using the Values property
'Reload the list from the hash table
collection lstLanguages.Items.Clear() For Each
strItem In mhshTable.Values
lstLanguages.Items.Add(strItem) Next
Using Stacks
Â
12Sorted Lists
'Create the key strKey strItem.Substring(0,
3) 'Add the key and item to the sorted
list msrtList.Add(strKey, strItem)
- A list of key and value pairs automatically
sorted by the key - Use the Add, Remove, and RemoveAt methods
- Access elements by key, by value, or by index
- Keys must be unique and may be created from a
hash code calculation
'Retrieve the selected item to be removed strItem
lstLanguages.SelectedItem.ToString 'Set the key
as the first three characters of the item strKey
strItem.Substring(0, 3) 'Remove the item by
key msrtList.Remove(strKey)
Using Stacks
'Remove the item by index msrtList.RemoveAt(intInd
ex)
Â
13Sorted Lists
- Sorted lists work well when you need to
add/remove items from the middle of the list. - Items can be removed from a list by index (but
indexes change as items are added or deleted). - Refer to the collection of items in a sorted list
using the Values property.
'Reload the list box from the sorted list
collection lstLanguages.Items.Clear() For Each
strItem In msrtList.Values
lstLanguages.Items.Add(strItem) Next
Using Stacks
Â
14Using Array Lists
- Dynamically increase in size as new elements are
added - Use the Capacity property to set the size of the
list - Capacity is automatically increased in chunks as
elements are added - Use the TrimToSize method to reduce the size of
the collection
Using Stacks
Â
15Using Array Lists
Using Stacks
Â
16Using Array Lists
Using Stacks
Â
17Creating a Collection of Objects
- Create a collection class and add objects to the
collection - Choose the collection class type based on needs
for speed, sorting, retrieval by value, index, or
key - Refer to the member of a collection in two ways
- Specify an index number
- Give each object a unique string key (PIN,
customer number, account number)
Creating a Collection of Objects
18A Collection of Student Objects
- Create and access a collection of student objects
Creating a Collection of Objects
19Declaring a Collection
- Declare and instantiate the collection at the
module level. - Example uses a sorted list and a hash code of the
name as the key
Dim colStudents As New SortedList()
Creating a Collection of Objects
20Adding Objects to a Collection
- Create the key using the GetHashCode method
- Convert the key to a string
- Add the object to the collection
'Declare and instantiate a new student. Dim
objStudent As New Student(txtName.Text,
CDec(txtGPA.Text)) 'Calculate a key strKey
objStudent.Name.GetHashCode.ToString 'Add to the
collection colStudents.Add(strKey, objStudent)
Creating a Collection of Objects
21Removing an Element from a Collection
- Remove method deletes by key
- RemoveAt removes by index
With lstStudents If .SelectedIndex ltgt -1
Then 'Get the key from the selected
student name Dim strKey As String
.SelectedItem.GetHashCode.ToString
colStudents.Remove(strKey)
DisplayList() Else
MessageBox.Show("Select a student from the
list.", _ "A Collection of
Students") End If End With
Creating a Collection of Objects
22Retrieving an Element from a Collection
- Use the Item property to retrieve an object from
a list. - Dictionary-type collections (sorted lists and
hash tables) return an object of DictionaryEntry
data type. - Cast the element to the object type needed.
Dim objStudent As Student  'Get the key for the
selected name Dim strKey As String
.SelectedItem.GetHashCode.ToString objStudent
CType(colStudents.Item(strKey), Student)
Creating a Collection of Objects
23Using For Each / Next
- Use a For Each/Next structure to access each
object in a collection
'Loop through the collection and display the
items in a list box Dim objStudent As Student Dim
deStudent As DictionaryEntry  lstStudents.Items.C
lear() For Each deStudent In colStudents
objStudent CType(deStudent.Value, Student)
lstStudents.Items.Add(objStudent.Name) Next
Creating a Collection of Objects
24Using an Items Collection
- The Items collection of a text box or combo box
is a collection of objects. - If necessary, write a ToString method to override
the base class
'Procedure in the Client class Public Overrides
Function ToString() As String 'Return the
Name property for this object's ToString method
Return mstrName End Function
Using an Items Collection
25Using an Items Collection
Using an Items Collection
- Add an object to a list box Items collection
- Convert the DictionaryEntry data type to the
correct type - Retrieve, convert, and reference individual
properties of the object.
lstClients.Items.Add(objClient)
objClient CType(.Items(.SelectedIndex), Client)
objClient CType(.Items(.SelectedIndex),
Client) MessageBox.Show("The phone number for "
objClient.Name " is " _ objClient.PhoneNumbe
r)