Web.nuu.edu.tw



VB Data Structure Basic supports a number of data structures called Collections that holds data in different ways for flexible operations. The important data structures in the Collection Classes are? HYPERLINK "" ArrayList?,? HYPERLINK "" HashTable?,?Stack?,?Queue?etc. From the following chapters you can see how to manage these data structures in your visual programs.How to use ArrayList ArrayList ExampleHow to use HashTable HashTable ExampleHow to use Stack Stack ExampleHow to use Queue Queue ExampleHow to use Arrays Arrays ExampleHow to use Dyanamic Arrays Dyanamic Arrays ExampleHow to use NameValueCollection NameValueCollection ExampleHow to use List List Dictionary example Dictionary exampleHow to: Declare a Structure StructureHow to ArrayListArrayList is one of the most flexible data structure from Collections. With the Array list you can add elements to your array dynamically and it accepts null as a valid value and also allows duplicate elements. Normally Collection class allow you to access an item using either a numeric index or a String key, but ArrayList allows only a numeric index. ArrayList is flexible because we can add items without any size information.vb-arraylistImportant functions from ArrayList ObjectAdd: Add Items in an ArrayListInsert: Insert Items to a specified position in an ArrayListRemove: Remove an Item from ArrayListRemoveAt: remove an item from a specified positionSort: Sort Items in an ArrayListHow to add Items in an ArrayList ?Syntax : ArrayList.add(Item)Item : The Item to be add the ArrayListDim ItemList As New ArrayList()ItemList.Add("Item4")How to Insert Items in an ArrayList ?Syntax : ArrayList.insert(index,item)index : The position of the item in an ArrayListItem : The Item to be add the ArrayListItemList.Insert(3, "item6")How to remove an item from arrayList ?Syntax : ArrayList.Remove(item)Item : The Item to be add the ArrayListItemList.Remove("item2")How to remove an item in a specified position from an ArrayList ?Syntax : ArrayList.RemoveAt(index)index : the position of an item to remove from an ArrayListItemList.RemoveAt(2)How to sort ArrayList ?Syntax : ArrayListSort()From the following Visual Basic source code you can see some important operations from an ArrayList ObjectPublic Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer Dim ItemList As New ArrayList() ItemList.Add("Item4") ItemList.Add("Item5") ItemList.Add("Item2") ItemList.Add("Item1") ItemList.Add("Item3") MsgBox("Shows Added Items") For i = 0 To ItemList.Count - 1 MsgBox(ItemList.Item(i)) Next 'insert an item ItemList.Insert(3, "Item6") 'sort itemms in an arraylist ItemList.Sort() 'remove an item ItemList.Remove("Item1") 'remove item from a specified index ItemList.RemoveAt(3) MsgBox("Shows final Items the ArrayList") For i = 0 To ItemList.Count - 1 MsgBox(ItemList.Item(i)) Next End SubEnd ClassWhen you execute this program , it add five items in the arraylist and displays using a for loop statement. Then again one more item inserted in the third position , and then sort all items. Next it remove the item1 and also remove the item from the third position . Finally it shows the existing items.How to HashTableHashTable stores a Key Value pair type collection of data . We can retrive items from hashTable to provide the key . Both key and value are Objects.The common functions using in Hashtable are :Add : To add a pair of value in HashTableSyntax : HashTable.Add(Key,Value)Key : The Key valueValue : The value of corrosponding keyContainsKey : Check if a specified key exist or notSynatx : HashTable.ContainsKey(key)Key : The Key value for search in HahTableContainsValue : Check the specified Value exist in HashTableSynatx : HashTable.ContainsValue(Value)Value : Search the specified Value in HashTableRemove : Remove the specified Key and corrosponding ValueSyntax : HashTable.Remove(Key)Key : The argument key of deleting pairsThe following source code shows all important operations in a HashTablePublic Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim weeks As New Hashtable Dim day As DictionaryEntry weeks.Add("1", "Sun") weeks.Add("2", "Mon") weeks.Add("3", "Tue") weeks.Add("4", "Wed") weeks.Add("5", "Thu") weeks.Add("6", "Fri") weeks.Add("7", "Sat") 'Display a single Item MsgBox(weeks.Item("5")) 'Search an Item If weeks.ContainsValue("Tue") Then MsgBox("Find") Else MsgBox("Not find") End If 'remove an Item weeks.Remove("3") 'Display all key value pairs For Each day In weeks MsgBox(day.Key " -- " day.Value) Next End SubEnd ClassWhen you execute this program it add seven weekdays in the hashtable and display the item 5. Then it check the item "Tue" is existing or not . Next it remove the third item from HashTable. Finaly it displays all item exist in the HashTable.How to Create StackStack is one of another easy to use Collections . Stack follows the push-pop operations, that is we can Push Items into Stack and Pop it later also it follows the Last In First Out (LIFO) system. That is we can push the items into a stack and get it in reverse order. Stack returns the last item monly used methods :Push : Add (Push) an item in the stack datastructureSyntax : Stack.Push(Object)Object : The item to be inserted.Pop : Pop return the item last Item to insert in stackSyntax : Stack.Pop()Return : The last object in the StackContains : Check the object contains in the stackSyntax : Stack.Contains(Object)Object : The specified Object to be searchThe following Source code shows some of commonly used functions :Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim stackTable As New Stack stackTable.Push("Sun") stackTable.Push("Mon") stackTable.Push("Tue") stackTable.Push("Wed") stackTable.Push("Thu") stackTable.Push("Fri") stackTable.Push("Sat") If stackTable.Contains("Wed") Then MsgBox(stackTable.Pop()) Else MsgBox("not exist") End If End SubEnd ClassWhen you execute this program add seven items in the stack . Then its checks the item "Wed" exist in the Stack. If the item exist in the Stack , it Pop the last item from Stack , else it shows the msg "Not Exist" How to QueueThe Queue is another adtastructure from Collections . Queue works like First In First Out method and the item added first in the Queue is first get out from Queue. We can Enqueue (add) items in Queue and we can Dequeue (remove from Queue ) or we can Peek (that is get the reference of first item added in Queue ) the item from Queue.The commonly using functions are follows :Enqueue : Add an Item in QueueSyntax : Stack.Enqueue(Object)Object : The item to add in QueueDequeue : Remove the oldest item from Queue (we don't get the item later)Syntax : Stack.Dequeue()Returns : Remove the oldest item and return.Peek : Get the reference of the oldest item (it is not removed permenantly)Syntax : Stack.Peek()returns : Get the reference of the oldest item in the QueueThe following Source code shows some of commonly used functions :Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object,_ByVal e As System.EventArgs) Handles Button1.Click Dim queueList As New Queue queueList.Enqueue("Sun") queueList.Enqueue("Mon") queueList.Enqueue("Tue") queueList.Enqueue("Wed") queueList.Enqueue("Thu") queueList.Enqueue("fri") queueList.Enqueue("Sat") MsgBox(queueList.Dequeue()) MsgBox(queueList.Peek()) If queueList.Contains("Sun") Then MsgBox("Contains Sun ") Else MsgBox("Not Contains Sun ") End If End SubEnd ClassWhen you execute the program it add seven items in the Queue. Then it Dequeue (remove) the oldest item from queue. Next it Peek() the oldest item from Queue (shows only , not remove ). Next it check the Item "Sun" contains in the Queue.How to ArraysArrays are using for store similar data types grouping as a single unit. It is a fixed collection of same data type that are stored contiguously and that are accessible by an index We specify their length and we can initialize arrays with data. We can access Array elements by its numeric index. arrayInteger ArrayDeclaring and Initializing an Integer ArrayDim array As Integer() = New Integer(3) {} array(0) = 10array(1) = 20array(2) = 30array(3) = 40In the above code we declare an Integer Array of four elements and assign the value to array index . That means we assign values to array index 0-3.We can retrieve these values from array by using a for loop.Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim array As Integer() = New Integer(3) {} array(0) = 10 array(1) = 20 array(2) = 30 array(3) = 40 For i As Integer = 0 To array.Length - 1 MessageBox.Show(array(i)) Next End SubEnd ClassWe can declare and initialize an array in one statement.Dim array As Integer() = New Integer() {10, 20, 30, 40}Note that in the above code we did not specify the length of the array so the compiler will do it for us.How to find the length of an Array ?array.LengthWe can use array.Length to find the length of an Array.String ArrayDeclaring and Initializing a String ArrayDim week(6) As StringThe above statements means that , an Array named as week declared as a String type and it can have the capability of seven String type values.week(0) = "Sunday"week(1) = "Monday"In the above statement , we initialize the values to the String Array. week(0) = "Sunday" means , we initialize the first value of Array as "Sunday" ,Dim weekName as String = week(1)We can access the Arrays elements by providing its numerical index, the above statement we access the second value from the week Array.In the following program , we declare an Array "week" capability of seven String values and assigns the seven values as days in a week . Next step is to retrieve the elements of the Array using a For loop. For finding the end of an Array we used the Length function of Array Object.Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer Dim week(6) As String week(0) = "Sunday" week(1) = "Monday" week(2) = "Tuesday" week(3) = "Wednesday" week(4) = "Thursday" week(5) = "Friday" week(6) = "Saturday" For i = 0 To week.Length - 1 MsgBox(week(i)) Next End SubEnd ClassHow to resize an array ?An array can be resized with Array.Resize < T > Method , that means We make an array bigger or smaller. Array.Resize < T > Method Changes the number of elements of a one-dimensional array to the specified new size.Array.Resize < T > - T is the type of the elements of the array.This method should be used with only one dimensional Array. This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim sArray As Char() = New Char(4) {} sArray(0) = "A" sArray(1) = "B" sArray(2) = "C" sArray(3) = "D" sArray(4) = "E" For i As Integer = 0 To sArray.Length - 1 MessageBox.Show(sArray(i).ToString()) Next Array.Resize(sArray, 3) For i As Integer = 0 To sArray.Length - 1 MessageBox.Show(sArray(i).ToString()) Next End SubEnd ClassArray.Resize(sArray, 3)In the above code we resize the array to 3 elements.How to Use For Each loop with Arrays ?Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim array As Integer() = {10, 30, 50} 'array declaration For Each element As Integer In array MsgBox(element) Next End SubEnd ClassArray Sortsort array in ascending descending Reverse arrayYou can sort the arrays in ascending order as well as descending . We can use Array.Sort method for sorts the elements in a one-dimensional array. Also we can use Array.Reverse method for reverses the sequence of the elements in the entire one-dimensional Array. Click the following link to see ....How to sort ArraysThe following source code shows how to sort an integer Array in ascending order.Dim arr As Integer() = New Integer() {3, 1, 4, 5, 2}Array.Sort(arr)For Each str As Integer In arr MsgBox(str)NextThe following code shows how to sort an Integer array in reverse order.Dim arr As Integer() = New Integer() {3, 1, 4, 5, 2}Array.Sort(arr)Array.Reverse(arr)For Each str As Integer In arr MsgBox(str)NextHow to Create an Array with different data typesYou can create an array with elements of different data types when declare the array as Object. Since System.Object is the base class of all other types, an item in an array of Objects can have a reference to any other type of object. More about.... Multiple data types in an Array - System.Array.CopyTo and System.Array.Clone()The System.Array.CopyTo method copies the elements into another pre-existing array starting from a given index. The System.Array.Clone() method returns a new array object, which means that the destination array need not exist yet since a new one is created from scratch with containing all the elements in the original array. More about the difference between .... System.Array.CopyTo and System.Array.Clone()How to check if a value exists in an array ?The following program shows how to find a specified value from an Array.Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim stringToCheck As String = "GHI" Dim stringArray As String() = {"ABC", "DEF", "GHI", "JKL"} For Each x As String In stringArray If x.Equals(stringToCheck) Then MessageBox.Show("Find the string ..." + x) End If Next End SubEnd ClassWhen you execute this program you will get the Days in a Week .How to Dyanamic ArrayDynamic Arrays can resize the capability of the Array at runtime .when you are in a situation that you do not know exactly the number of elements to store in array while you making the program. In that situations we are using Dynamic Array .Initial declarationDim scores() As IntegerResizingReDim scores(1)If you want to keep the existing items in the Array , you can use the keyword Preserve .ReDim Preserve scores(2)In this case the Array dynamically allocate one more String value and keep the existing values.Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer Dim scores() As Integer ReDim scores(1) scores(0) = 100 scores(1) = 200 For i = 0 To scores.Length - 1 MsgBox(scores(i)) Next ReDim Preserve scores(2) scores(2) = 300 For i = 0 To scores.Length - 1 MsgBox(scores(i)) Next End SubEnd ClassWhen you execute this source code , the first loop shows first two values stored in the Array. Next loop shows the whole value stored in the Array.How to NameValueCollectionNameValueCollection is used to store data like Name, Value format. It is very similar to HashTable, HashTable also stores data in Key , value format . NameValueCollection can hold more than one value for a corresponding Key.Adding new pairsAdd(ByVal name As String, ByVal value As String)Add("High","80")Get the value of corresponding KeyGetValues(ByVal name As String) As String()String values() = GetValues("High")Imports System.Collections.SpecializedPublic Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim markStatus As New NameValueCollection Dim key As String Dim values() As String markStatus.Add("Very High", "80") markStatus.Add("High", "60") markStatus.Add("medium", "50") markStatus.Add("Pass", "40") For Each key In markStatus.Keys values = markStatus.GetValues(key) For Each value As String In values MsgBox(key & " - " & value) Next value Next key End SubEnd ClassWhen you execute this source code , you will get each Key/Value sets.How to DictionaryA Dictionary class is a data structure that represents a collection of keys and values pair of data. Each item is a combination of a key and a value. ( key-value pair)Syntax: dictionary sampleParameters :TKey - The type of the keys in the alue - The type of the values in the dictionary.e.g.Dim dict As New Dictionary(Of String, Integer)()Adding Values to DictionaryAdd method in Dictionary takes two parameters, one for the key and one for the value.Syntax:public void Add(TKey key,TValue value)e.g.dictionary.Add("dozen",12)Key in a Dictionary should not be null, but a value can be, if TValue is a reference type.Dim dict As New Dictionary(Of String, Integer)()dict.Add("one", 1)dict.Add("two", 2)dict.Add("three", 3)dict.Add("four", 4)Retrieve Key-Value pair from DictionaryWe can retrieve values from Dictionary using foreach loopFor Each pair As KeyValuePair(Of String, Integer) In dict MsgBox(pair.Key & " - " & pair.Value)NextSearch for a KeyWe can search a Key in Dictionary by using the ContainsKey method to test whether a key exists or not. ContainsKey computes the hashcode for its argument and checks the internal structures in the Dictionary.If dict.ContainsKey("four") = True Then MessageBox.Show(dict("four").ToString())Else MessageBox.Show("Key does not exist")End IfIterate over a DictionaryThere are many different ways to iterate over a Dictionary in . From the following link you can see in detail .... How to Iterate over a DictionaryDictionary Versus Dictionary and HashTableDictionary is a generic type, Hashtable is not. That means you get type safety with Dictionary, because you can't insert any random object into it, and you don't have to cast the values you take out. Since both Dictionary and Hashtable are internally hashtables, so fast access to many-item data according to key, also both need immutable and unique keys. More about.... Dictionary Vs HashTableDictionary Versus Dictionary and ListBoth lists and dictionaries are used to store collections of data. The Dictionary is based on a hash table, that means it uses a hash lookup, which is a rather efficient algorithm to look up things, on the other hand, a list you have to go element by element until it finds the result from beginning to the result each time. More about.... Dictionary vs ListFollowing program is a full source code of adding and retrieving key values pairs in DictionaryDim dict As New Dictionary(Of String, Integer)()dict.Add("one", 1)dict.Add("two", 2)dict.Add("three", 3)dict.Add("four", 4)For Each pair As KeyValuePair(Of String, Integer) In dict MsgBox(pair.Key & " - " & pair.Value)NextHow to use List examplesGeneric lists were introduced with .Net 2.0 and are the way to go. List is a generic implementation of ArrayList. List can store only one type of objects, that type supplied as its generic parameter. List class is a collection and defined in the System.Collections.Generic namespace and it provides the methods and properties like other Collection classes such as add, insert, remove, search etc.To use List(Of T), however, you have to understand how to implement the many methods that the .NET Framework providesList(Of T)The parameter T is the type of elements in the list.How to add items in List ?Add integer values in the ListDim iList As New List(Of Integer)()iList.Add(2)iList.Add(3)iList.Add(5)iList.Add(7)Add string values in the ListDim numbers As New List(Of String)()numbers.Add("One")numbers.Add("Two")numbers.Add("Three")How to count number of items exists in a List ?List.Count property gives you the number of items exists in Listnumbers.CountHow to retrieve items from List ?You can retrieve items from List collection by using for loops.for each loopFor Each number As String In numbersMessageBox.Show(number)Nextfor loopFor i As Integer = 0 To numbers.Count - 1MessageBox.Show(numbers(i))NextHow to insert an item in the List ?You can use insert(index,item) method to insert an in the specified index. numbers.Insert(1, "zero")In the above code the number "zero" is inserted in the index position 1.How to remove an item from List collection?List.Remove() can use to remove item from List.numbers.Remove("zero");How to check if an item exist in the List ?You can use List.Contains() method to check an item exists in the Listif (numbers.Contains("Two")){MessageBox.Show("Number Two exist in the list");}How to copy an Array to a List ?Dim strArr As String() = New String(2) {}strArr(0) = "Red"strArr(1) = "Blue"strArr(2) = "Green"//here to copy array to ListDim arrlist As New List(Of String)(strArr)Finally clear method remove all the items from List collection.arrlist.Clear()Difference between list and dictionary in In applications both lists and dictionaries are used to store collections of data. List (ICollection ) is simply a set of items and Dictionary(IDictionary) is a set of key-value pairs. The essential difference therefore is in how the containers are indexed data in your application. If you want to know more details.....What is the difference between list and dictionary in ?The following program shows the implementation of the above functionalities in List collection.Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim numbers As New List(Of String)() 'add items in a List collection numbers.Add("One") numbers.Add("Two") numbers.Add("Three") 'insert an item in the list numbers.Insert(1, "Zero") 'retrieve items using foreach loop For Each number As String In numbers MessageBox.Show(number) Next 'remove an item from list numbers.Remove("Zero") 'retrieve items using for loop For i As Integer = 0 To numbers.Count - 1 MessageBox.Show(numbers(i)) Next If numbers.Contains("Two") Then MessageBox.Show("Number two exist in the list") Else MessageBox.Show("Not exist") End If 'copy array to list Dim strArr As String() = New String(2) {} strArr(0) = "Red" strArr(1) = "Blue" strArr(2) = "Green" Dim arrlist As New List(Of String)(strArr) For Each str As String In strArr MessageBox.Show(str) Next 'call clear method arrlist.Clear() MessageBox.Show(arrlist.Count.ToString()) End SubEnd ClassHow to: Declare a Structure. Create the beginning and ending statements for the structure.You can specify the access level of a structure using the Public, Protected, Friend, or Private keyword, or you can let it default to Public.Private Structure employee End Structure 2. Add elements to the body of the structure.A structure must have at least one element. You must declare every element and specify an access level for it. If you use the Dim Statement without any keywords, the accessibility defaults to Public.Example: Private Structure employee Public givenName As String Public familyName As String Public phoneExtension As Long Private salary As Decimal Public Sub giveRaise(raise As Double) salary *= raise End Sub Public Event salaryReviewTime() End Structure The salary field in the preceding example is Private, which means it is inaccessible outside the structure, even from the containing class. However, the giveRaise procedure is Public, so it can be called from outside the structure. Similarly, you can raise the salaryReviewTime event from outside the structure. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download