更新:2007 年 11 月
与任何对象一样,声明一个变量以存储对象,然后创建集合对象并将它赋给变量。
对于集合对象,可以使用Visual Basic 集合类或 .NET Framework 集合类。特别是,可以通过使用 System.Collections.Generic 命名空间中的某个类来创建“泛型”集合。当泛型集合中的所有项具有相同的数据类型时,泛型集合很有用。泛型集合通过仅允许添加所需的数据类型来执行“强类型”。有关更多信息,请参见如何:定义类型安全集合。
创建了集合对象后,可以添加和移除集合中的项或访问集合中的项。
以下是有关如何创建集合的两个示例。每个集合都存储 String 项并将 String 键与每个项关联。前两个过程使用 Visual Basic 集合类创建集合。后两个过程使用 .NET Framework 泛型集合类创建集合。
使用 Visual Basic 集合类创建集合
- 声明和创建 Visual BasicCollection 变量,如下例所示。 - Dim sampleVisualBasicColl As New Microsoft.VisualBasic.Collection()- sampleVisualBasicColl 中的集合可以接受任何数据类型的项。 
- 使用 Add 方法(Collection 对象) 将元素添加到集合中。下面的示例创建四个 String 元素并将这些元素添加到集合中。它创建一个唯一的 String 值作为每个新元素的键,并将该值传递给 Add 方法。 - 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")- Key 参数在 Visual Basic 集合中是可选的。 
- 如果要从集合中移除元素,可以使用 Remove 方法(Collection 对象),通过位置索引或可选的键来标识元素。下面的示例阐释这一点。 - ' Remove the first element of the Visual Basic collection. sampleVisualBasicColl.Remove(1) ' Remove the element with the key "secondkey". sampleVisualBasicColl.Remove("secondkey")- 请注意,从 Visual BasicCollection 中移除元素时,索引值从 1 到 Count 属性(Collection 对象) 的值重新编号。 
使用 For Each...Next 处理 Visual Basic 集合的元素
- 声明集合中存储的类型的变量。对于前面的示例,声明 String 类型的变量,如下例所示。 - ' Insert code from the preceding example. Dim aString As String
- 使用 For Each...Next 语句 (Visual Basic) 检查集合的每个元素。下面的示例搜索特定的字符串并在找到后显示该字符串。 - For Each aString in sampleVisualBasicColl If aString = "Collection" Then MsgBox(aString) End If Next aString
使用泛型集合类创建集合
- 声明和创建 .NET FrameworkSystem.Collections.Generic.Dictionary<TKey, TValue> 变量,如下例所示。 - Dim sampleGenericColl As New System.Collections.Generic.Dictionary(Of String, String)- sampleGenericColl 变量存储“类型安全”的集合,该集合仅接受 String 类型的项和键。 
- 使用 Dictionary<TKey, TValue>.Add 方法将元素添加到集合中。下面的示例创建四个 String 元素并将这些元素添加到集合中。它创建一个唯一的 String 值作为每个新元素的键,并将该值传递给 Add 方法。 - 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)- Key 参数在泛型集合中是必选的。 
- 若要从集合中移除元素,请使用 IDictionary<TKey, TValue>.Remove 方法。必须提供键来标识要移除的元素。下面的示例阐释这一点。 - If Not sampleGenericColl.Remove("thirdkey") ' Insert code to handle "thirdkey" not found in collection. End If- 可以使用 For Each...Next 语句依次查看和处理集合的元素,如以下过程所示。 
使用 For Each...Next 处理泛型集合的元素
- 声明集合中存储的类型的变量。对于前面的示例,声明 String 类型的变量,如下例所示。 - ' Insert code from the preceding example. Dim aPair As KeyValuePair(Of String, String)
- 使用 For Each...Next 语句 (Visual Basic) 检查集合的每个元素。下面的示例搜索特定的字符串并在找到后显示该字符串。 - For Each aPair In sampleGenericColl If aPair.Value = "Items" Then MsgBox(aPair.Key & " -- " & aPair.Value) End If Next aPair