Collections

VB.NET supports collections such as List and Dictionary, which are useful constructs when building applications that need to access a set of related information.

When building Lists containing objects, the Of keyword is used in the definition.

New elements are added to the List using its Add method.

                       

Dictionary collections work similarly to Lists with the addition of a "key" portion to each element.

The data type KeyValuePair is useful when iterating through a Dictionary collection as the example below demonstrates.

The Dictionary method ContainsKey returns true if the parameter is found as a key value in the Dictionary object.



The Collections' Count property returns an Integer containing the number of members in the collection.

The Item method returns the member of the collection for the specified key.

Dim animal As Animal
animal = Zoo.Item(0) ' return the first animal in the Zoo List



The Remove method removes a member from a collection.

Zoo.Remove(animal) ' remove the first animal in the Zoo List (see above)



The following will not work because the new animal object is not an Animal object that is directly referenced within the Zoo List (even though it is defined the same)

animal = New Animal( "lion", "roar")
Zoo. Remove( animal)



The RemoveAt method removes a member from a collection at a specified index.

Zoo. RemoveAt(0) ' remove the current first animal in the Zoo List



Collections also support methods Sort and Reverse.



MSDN: Example using the Dictionary collection in VB from the MSDN site

 

posted @ 2015-06-17 14:54  xymum  阅读(96)  评论(0编辑  收藏  举报