Compartilhar via


Como: Criar uma coleção de objetos (Visual Basic)

As with any object, you declare a variable to hold the object, and then create the collection object and assign it to the variable.

objetode uma coleção, você pode usar o Collectionclasse ou um .NET Frameworkclassedecoleção. In particular, you can create a generic collection by using one of the classes in the System.Collections.Generic namespace. A generic collection is useful when every item in the collection has the same data type. Generic collections enforce strong typing by allowing only the desired data type to be added. For more information, see Como: Definir coleções fortemente tipadas (Visual Basic).

Once the collection object is created, you can add and remove items and access items in the collection.

Two examples about how to create collections follow. Each collection holds String items and associates a String key with each item. The first two procedures create a collection using the Visual Basic collection class. The last two procedures create a collection using a .NET Framework generic collection class.

To create a collection using the Visual Basic collection class

  1. Declarar e criar um Visual Basic Collection variável, conforme o exemplo a seguir mostra.

    Dim sampleVisualBasicColl As New Microsoft.VisualBasic.Collection()
    

    The collection in sampleVisualBasicColl can accept items of any data type.

  2. Use the Add method to add elements to the collection. The following example creates four String elements and adds them to the collection. It creates a unique String value as the key for each new element and passes this value to the Add method.

    Dim item1, item2, item3, item4 As String
    item1 = "Items"
    item2 = "In"
    item3 = "A"
    item4 = "Collection"
    sampleVisualBasicColl.Add(item1, "firstkey")
    sampleVisualBasicColl.Add(item2, "secondkey")
    sampleVisualBasicColl.Add(item3, "thirdkey")
    sampleVisualBasicColl.Add(item4, "fourthkey")
    

    The Key argument is optional in a Visual Basic collection.

  3. Se você quiser remover um elemento da coleção, você pode usar o Remove método, identificando o elemento pelo índice posicional ou pela sua chavede opcionais. The following example illustrates this.

    ' Remove the first element of the Visual Basic collection.
    sampleVisualBasicColl.Remove(1)
    ' Remove the element with the key "secondkey".
    sampleVisualBasicColl.Remove("secondkey")
    

    Observe que, quando um elemento é removido de um Visual Basic Collection, os valores de índice são renumerados de 1 até o valor da Count propriedade.

To use For Each...Next to process the elements of your Visual Basic collection

  1. Declare a variable of the type stored in the collection. For the previous example, declare a variable of type String, as the following example shows.

    ' Insert code from the preceding example.
    Dim aString As String
    
  2. Use a Instrução For Each...Next (Visual Basic) to examine each element of the collection. The following example searches for a particular string and displays it if found.

    For Each aString in sampleVisualBasicColl
        If aString = "Collection" Then
            MsgBox(aString)
        End If
    Next aString
    

To create a collection using a generic collection class

  1. Declarar e criar um .NET Framework System.Collections.Generic.Dictionary<TKey, TValue> variável, conforme o exemplo a seguir mostra.

    Dim sampleGenericColl As New System.Collections.Generic.Dictionary(Of String, String)
    

    The sampleGenericColl variable holds a type-safe collection that accepts items and keys only of type String.

  2. Use the Dictionary<TKey, TValue>.Add method to add elements to the collection. The following example creates four String elements and adds them to the collection. It creates a unique String value as the key for each new element and passes this value to the Add method.

    Dim item1, item2, item3, item4 As String
    item1 = "Items"
    item2 = "In"
    item3 = "A"
    item4 = "Collection"
    sampleGenericColl.Add("firstkey", item1)
    sampleGenericColl.Add("secondkey", item2)
    sampleGenericColl.Add("thirdkey", item3)
    sampleGenericColl.Add("fourthkey", item4)
    

    The Key argument is required in this generic collection.

  3. To remove an element from the collection, use the IDictionary<TKey, TValue>.Remove method. You must supply the key to identify the element to remove. The following example illustrates this.

    If Not sampleGenericColl.Remove("thirdkey")
        ' Insert code to handle "thirdkey" not found in collection.
    End If
    

    You can use a For Each...Next statement to loop through and process the elements of a collection, as the following procedure demonstrates.

To use For Each...Next to process the elements of your generic collection

  1. Declare a variable of the type stored in the collection. For the previous example, declare a variable of type String, as the following example shows.

    ' Insert code from the preceding example.
    Dim aPair As KeyValuePair(Of String, String)
    
  2. Use a Instrução For Each...Next (Visual Basic) to examine each element of the collection. The following example searches for a particular string and displays it if found.

    For Each aPair In sampleGenericColl
        If aPair.Value = "Items" Then
            MsgBox(aPair.Key & " -- " & aPair.Value)
        End If
    Next aPair
    

Consulte também

Tarefas

Como: Criar uma matriz de objetos (Visual Basic)

Referência

Collection

System.Collections

System.Collections.Generic

System.Collections.Specialized