1 / 34

VB Collection Data Structures

VB Collection Data Structures Array ArrayList HashTable VB6 Collection Others:SortedList, Stack, Queue Arrays Declaring a Array With subscript: Dim numbers(2) as Integer Using variable as subscript: Dim arrayIndex as Integer = 10 Dim myArray(arrayIndex) as Integer Without subscript

andrew
Download Presentation

VB Collection Data Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. VB Collection Data Structures

  2. Array • ArrayList • HashTable • VB6 Collection • Others:SortedList, Stack, Queue

  3. Arrays

  4. Declaring a Array • With subscript: • Dim numbers(2) as Integer • Using variable as subscript: • Dim arrayIndex as Integer = 10 • Dim myArray(arrayIndex) as Integer • Without subscript • Dim numbers() as Integer = {2, 4, 6} • Dim someNames() as String = {“”, “”, “”} • Note: Can not have a subscript with a initialization list. • Without subscript and initialization • Dim numbers As Integer() • numbers = New Integer() {2, 4, 6}

  5. Accessing Array Elements with a For … Next Loop • Dim i As Integer = 0, sum As Integer = 0 • For i = 0 To 2 • sum += numbers(i) • Next • GetUpperBound • For i = 0 to numbers.GetUpperBound(0) sum += numbers(i) • Next • Length • For i = 0 to numbers.length-1 sum += numbers(i) • Next

  6. Accessing Array Elements with a For Each Loop Dim i As Integer For Each i In numbers i = i * 2 MessageBox.Show(i.ToString) Next

  7. Array’s Properties and Methods • Properties: • Length • IsFixedSize • IsReadOnly • Methods • BinarySearch *** return negative value if not found • Clear • Clone, Copy, CopyTo • GetLowerBound, GetUpperBound • Reverse • Sort

  8. Highest Values in a Array Dim highest As Integer highest = numbers(0) For i = 1 To numbers.GetUpperBound(0) If numbers(i) > highest Then highest = numbers(i) End If Next

  9. Searching Arrays Dim found As Boolean = False Dim searchValue As Integer searchValue = InputBox("Enter search value: ") For i = 0 To numbers.GetUpperBound(0) If numbers(i) = searchValue Then found = True Exit For End If Next If found Then MsgBox("Number found") Else MsgBox("Number not found") End If

  10. Searching with the IndexOf Method If numbers.IndexOf(numbers, InputBox("Enter search value: ")) < 0 Then MessageBox.Show("not exist") Else MessageBox.Show("exist") End If

  11. Using Parallel Relationship between Array and Listbox Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ListBox1.Items.Add("Peter") ListBox1.Items.Add("Paul") ListBox1.Items.Add("Mary") phone(0) = "1234" phone(1) = "6789" phone(2) = "3456" End Sub Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged MessageBox.Show(ListBox1.SelectedItem & "phone is" & phone(ListBox1.SelectedIndex)) End Sub

  12. ReDim • ReDim numbers(5) • Original values in the array will be lost. • ReDim Preserve numbers(5) • Use ReDim to assign size if the array is declared without subscript. • Dim test As Integer() • … • ReDim test(2)

  13. Passing Arrays as Arguments Dim outstr As String setnew(test) For i = 0 To test.GetUpperBound(0) outstr &= test(i).ToString & vbCrLf Next MessageBox.Show(outstr) End Sub Sub setnew(ByVal a() As Integer) Dim i As Integer For i = 0 To a.GetUpperBound(0) a(i) = 0 Next End Sub Note: ByVal or ByRef? With ByVal, it will prevent an array argument from being assigned to another array.

  14. Two-Dimensional Arrays • Depts=1 • Prods=2 • Dim SalesData(Depts, Prods) As Double • With initialization • Dim SalesData(,) as Double = {{20,30,15},{40,32,55}}

  15. For Each Loops for 2-dimensional Array Dim salesData(,) As Double = {{20, 15, 30}, {30, 21, 50}} Dim totalSales, I As Double For Each I In salesData totalSales += I Next TextBox1.Text = totalSales.ToString

  16. For Next Loops for 2-dimensional Array Dim row, col As Integer For row = 0 To salesData.GetUpperBound(0) For col = 0 To salesData.GetUpperBound(1) totalSales += salesData(row, col) Next Next MessageBox.Show(totalSales.ToString) Problem: How to compute total sales by Department? by Product?

  17. Data Binding with Arrays • Connect a control to one data source. • Arrays can be used as data source for a control. • Demo: ListBox DataSource property. • Dim fruits() As String = {"Apple", "Orange", "Banana", "Strawberry", "Kiwi"} • ListBox1.DataSource = fruits

  18. Other Collections • More flexible than array: • No need to declare the number of objects in a collection. • Objects can be added, deleted at any position. • Object can be retrieved from a collection by a key. • Can store any types of data.

  19. ArrayList • Define an arraylist: • Dim myArrayList As New ArrayList() • Properties:Count, Item, etc. • myArrayList.Item(0) 0-based index • Methods: • Clear, Add, Insert, Remove, RemoveAt, Contains, IndexOf, etc.

  20. ArrayList Demo Dim testArrayList As New ArrayList() Dim Fruits() As String = {"Apple", "orange", "Banana"} Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim f2 As New Form2() testArrayList.Add("David") testArrayList.Add(20) testArrayList.Add(Fruits) testArrayList.Add(f2) TextBox1.Text = testArrayList.Item(0) TextBox2.Text = testArrayList.Item(1).ToString TextBox3.Text = testArrayList.Item(2)(1) TextBox4.Text = testArrayList.Item(3).Age End Sub

  21. For Each Loop with ArrayList Dim testArrayList As New ArrayList() Dim f2 As New DataForm2() Dim Fruits() As String = {"Apple", "orange", "Banana"} testArrayList.Add("David") testArrayList.Add(20) testArrayList.Add(Fruits) testArrayList.Add(f2) Dim myObj As Object For Each myObj In testArrayList MessageBox.Show(myObj.GetType.ToString) Next

  22. Data Binding with ArrayLists • Arraylists can be used as data source for a control. • Demo: ListBox DataSource property. • Dim myArrayList As New ArrayList() • myArrayList.Add("apple") • myArrayList.Add("banana") • myArrayList.Add("orange") • ListBox1.DataSource = myArrayList

  23. Spelling Checker Example Dim wordList As New ArrayList Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load wordList.Add("This") wordList.Add("is") wordList.Add("a") wordList.Add("list") wordList.Add("of") wordList.Add("words") wordList.Add("that") wordList.Add("we") wordList.Add("will") wordList.Add("use") wordList.Add("in") wordList.Add("the") wordList.Add("spell") wordList.Add("checker") wordList.Add("david") wordList.Add("chao") wordList.Add(" ") End Sub

  24. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try Dim re As Regex re = New Regex("\w+") Dim source As String source = txtSource.Text Dim mc As MatchCollection = re.Matches(source) Dim m As Match Dim result As String For Each m In mc If Not wordList.Contains(m.Value) Then result += m.ToString & vbCrLf txtSource.Select(txtSource.Text.IndexOf(m.ToString), m.Length) MessageBox.Show("next") End If Next MessageBox.Show("Invalid words: " & vbCrLf & result) Catch ex As System.Exception MessageBox.Show(ex.Message) End Try End Sub

  25. HashTable • The HashTable collection provides very fast look-up. • Each element in a HashTable is a DictionaryEntry type containing a pair of Key and Value. • Properties:Count, Item, Keys, Values • myHashTable.Item(key) • Methods: • Clear, Add, Remove,ContainsKey, ContainsValue, etc. • Note 1: Elements in a HashTable are stored according to the hash value of keys. • Note 2: Keys must be unique.

  26. HashTable Example Dim myHashTable As New Hashtable() Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load myHashTable.Add("UK", "United Kingdom") myHashTable.Add("US", "United States") myHashTable.Add("CHN", "China") myHashTable.Add("DE", "Germany") Dim myKey As String For Each myKey In myHashTable.Keys ListBox1.Items.Add(myKey) Next End Sub Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged MessageBox.Show(myHashTable.Item(ListBox1.SelectedItem)) End Sub

  27. Dim searchKey As String searchKey = InputBox("enter key") If myHash.ContainsKey(searchKey) Then TextBox1.Text = myHashTable.Item(searchKey) Else MessageBox.Show("key not exists") End If

  28. VB 6 Collections • Define a collection: • Ex. Dim Pets as New Collection • Methods: • ADD: Add object to a collection • Pets.Add(“dog”) • Add an object with a key: • Pets.Add(“Dog”, “D”) • Item: Retrieve an object from a collection with a position index (base 1) or with a key. • petName = Pets.Item(1) • petName = Pets.Item(“D”) • Count: Return the number of objects in a collection. • Remove: Delete an object with a position index or key.

  29. Iterating Through a Collection Dim Pets as New Collection … Dim Indx as Long For Indx = 1 to Pets.Count …operations … Next Indx For Each pet in Pets … operations … Next pet

  30. Timer • Event: • Tick • Property: • Enable • Interval property • measured in millisecond, 1000 millis = 1 second • Methods: • Start • Stop

  31. Status Bar & Timer • Status Bar • Panels property (collection) • Set ShowPanel property to true. • StatusBar1.ShowPanels = True • StatusBarPanel1.Text = System.DateTime.Now.ToString • Timer • Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick StatusBarPanel1.Text = System.DateTime.Now.ToString End Sub

  32. Bitmap Data Type • To read a picture file to program: • Dim pic as New Bitmap(“c:\mypic.jpg”)

  33. Rotate Form’s Background Image Create a collection of pictures: Dim pcol As New ArrayList Add images to collection Dim im1 As New Bitmap("c:\Paradise.jpg") Dim im2 As New Bitmap("c:\Flyaway.jpg") Dim im3 As New Bitmap("c:\SnowTrees.jpg") pcol.Add(im1) pcol.Add(im2) pcol.Add(im3) Use Timer to change image

  34. Dim pcol As New ArrayList Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim im1 As New Bitmap("c:\Paradise.jpg") Dim im2 As New Bitmap("c:\Flyaway.jpg") Dim im3 As New Bitmap("c:\SnowTrees.jpg") pcol.Add(im1) pcol.Add(im2) pcol.Add(im3) End Sub Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick Static counter As Integer Me.BackgroundImage = pcol.Item(counter) counter += 1 counter = (counter Mod 3) End Sub

More Related