集合 (Visual Basic)

对于许多应用程序,需要创建和管理相关对象的组。 可通过两种方式对对象进行分组:创建对象的数组,以及创建对象的集合。

数组最适用于创建和使用固定数量的强类型对象。 有关数组的信息,请参阅 数组

集合提供了一种更灵活的方法来处理对象组。 与数组不同,随着应用程序需求的变化,你处理的对象组可以动态增长和收缩。 对于某些集合,可以将键分配给放入集合中的任何对象,以便使用键快速检索对象。

集合是一个类,因此必须先声明类的实例,然后才能将元素添加到该集合。

如果集合仅包含一个数据类型的元素,则可以在命名空间中使用 System.Collections.Generic 其中一个类。 泛型集合强制实施类型安全性,以便无法向其中添加其他数据类型。 从泛型集合中检索元素时,无需确定其数据类型或转换它。

注释

在本主题的示例中,针对 System.Collections.Generic 命名空间包括 System.Linq 语句。

使用简单集合

本节中的示例使用泛型 List<T> 类,可用于处理强类型对象列表。

以下示例创建一个字符串列表,然后使用 For Each…Next 语句遍历这些字符串。

' Create a list of strings.
Dim salmons As New List(Of String)
salmons.Add("chinook")
salmons.Add("coho")
salmons.Add("pink")
salmons.Add("sockeye")

' Iterate through the list.
For Each salmon As String In salmons
    Console.Write(salmon & " ")
Next
'Output: chinook coho pink sockeye

如果集合的内容事先已知,可以使用 集合初始值设定 项初始化集合。 有关详细信息,请参阅 集合初始值设定项

以下示例与前面的示例相同,但集合初始值设定项用于向集合中添加元素。

' Create a list of strings by using a
' collection initializer.
Dim salmons As New List(Of String) From
    {"chinook", "coho", "pink", "sockeye"}

For Each salmon As String In salmons
    Console.Write(salmon & " ")
Next
'Output: chinook coho pink sockeye

可以使用 For...Next 语句而不是使用 For Each 语句来迭代集合。 可以通过按索引位置访问集合元素来实现此目的。 元素的索引从 0 开始,在元素计数减 1 处结束。

下面的示例使用 For…Next 而不是 For Each循环访问集合的元素。

Dim salmons As New List(Of String) From
    {"chinook", "coho", "pink", "sockeye"}

For index = 0 To salmons.Count - 1
    Console.Write(salmons(index) & " ")
Next
'Output: chinook coho pink sockeye

以下示例通过指定要删除的对象从集合中删除元素。

' Create a list of strings by using a
' collection initializer.
Dim salmons As New List(Of String) From
    {"chinook", "coho", "pink", "sockeye"}

' Remove an element in the list by specifying
' the object.
salmons.Remove("coho")

For Each salmon As String In salmons
    Console.Write(salmon & " ")
Next
'Output: chinook pink sockeye

以下示例从泛型列表中删除元素。 不是使用 For Each 语句,而是采用一个以降序迭代的 For…Next 循环语句。 这是因为该方法 RemoveAt 导致移除的元素后元素具有较低的索引值。

Dim numbers As New List(Of Integer) From
    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

' Remove odd numbers.
For index As Integer = numbers.Count - 1 To 0 Step -1
    If numbers(index) Mod 2 = 1 Then
        ' Remove the element by specifying
        ' the zero-based index in the list.
        numbers.RemoveAt(index)
    End If
Next

' Iterate through the list.
' A lambda expression is placed in the ForEach method
' of the List(T) object.
numbers.ForEach(
    Sub(number) Console.Write(number & " "))
' Output: 0 2 4 6 8

对于元素 List<T>的类型,还可以定义自己的类。 在下面的示例中,由 Galaxy 使用的 List<T> 类在代码中定义。

Private Sub IterateThroughList()
    Dim theGalaxies As New List(Of Galaxy) From
        {
            New Galaxy With {.Name = "Tadpole", .MegaLightYears = 400},
            New Galaxy With {.Name = "Pinwheel", .MegaLightYears = 25},
            New Galaxy With {.Name = "Milky Way", .MegaLightYears = 0},
            New Galaxy With {.Name = "Andromeda", .MegaLightYears = 3}
        }

    For Each theGalaxy In theGalaxies
        With theGalaxy
            Console.WriteLine(.Name & "  " & .MegaLightYears)
        End With
    Next

    ' Output:
    '  Tadpole  400
    '  Pinwheel  25
    '  Milky Way  0
    '  Andromeda  3
End Sub

Public Class Galaxy
    Public Property Name As String
    Public Property MegaLightYears As Integer
End Class

集合的类型

.NET Framework 提供了许多常见集合。 每种类型的集合都设计为特定用途。

本节介绍了一些常见集合类:

System.Collections.Generic 类

可以使用命名空间中的 System.Collections.Generic 一个类来创建泛型集合。 当集合中的每个项具有相同的数据类型时,泛型集合非常有用。 泛型集合通过仅允许添加所需的数据类型,强制实施强类型化。

下表列出了命名空间的一些常用类 System.Collections.Generic

班级 DESCRIPTION
Dictionary<TKey,TValue> 表示基于键进行组织的键/值对的集合。
List<T> 表示可通过索引访问的对象列表。 提供用于搜索、排序和修改列表的方法。
Queue<T> 表示对象的先进先出 (FIFO) 集合。
SortedList<TKey,TValue> 表示基于相关的 IComparer<T> 实现按键进行排序的键/值对的集合。
Stack<T> 表示对象的后进先出 (LIFO) 集合。

有关详细信息,请参阅 常用集合类型选择集合类System.Collections.Generic

System.Collections.Concurrent 类

在 .NET Framework 4 或更高版本中,命名空间中的 System.Collections.Concurrent 集合提供高效的线程安全作,用于从多个线程访问集合项。

每当多个线程同时访问集合时,应使用命名空间中的System.Collections.Concurrent类,而不是命名空间中的System.Collections.GenericSystem.Collections相应类型。 有关详细信息,请参阅 Thread-Safe 集合System.Collections.Concurrent

命名空间中包含的System.Collections.Concurrent一些类是BlockingCollection<T>ConcurrentDictionary<TKey,TValue>ConcurrentQueue<T>ConcurrentStack<T>

System.Collections 类

命名空间中的 System.Collections 类不将元素存储为特定类型对象,而是存储为类型的 Object对象。

尽可能使用System.Collections.Generic命名空间或System.Collections.Concurrent命名空间中的泛型集合,而不是使用System.Collections命名空间中的旧版类型。

下表列出了命名空间中 System.Collections 一些常用类:

班级 DESCRIPTION
ArrayList 表示一个对象数组,其大小根据需要动态增加。
Hashtable 表示根据键的哈希代码进行组织的键/值对的集合。
Queue 表示对象的先进先出 (FIFO) 集合。
Stack 表示对象的后进先出 (LIFO) 集合。

命名空间 System.Collections.Specialized 提供专用的强类型集合类,例如仅字符串集合、链接列表和混合字典。

Visual Basic 集合类

可以使用 Visual Basic Collection 类通过数字索引或 String 键来访问集合项。 可以使用或不指定键将项添加到集合对象。 如果添加没有键的项,则必须使用其数值索引来访问它。

Visual Basic Collection 类将所有元素存储为类型 Object,因此可以添加任何数据类型的项。 无法防止添加不适当的数据类型。

使用 Visual Basic Collection 类时,集合中的第一个项的索引为 1。 这不同于 .NET Framework 集合类,其中起始索引为 0。

尽可能使用System.Collections.Generic命名空间或System.Collections.Concurrent命名空间中的泛型集合,而不是 Visual Basic Collection 类。

有关详细信息,请参阅 Collection

实现键/值对集合

使用 Dictionary<TKey,TValue> 泛型集合,可以使用每个元素的键访问集合中的元素。 字典的每个添加都包含一个值及其关联的键。 使用其键检索值的速度很快,因为该 Dictionary 类作为哈希表实现。

以下示例创建一个 Dictionary 集合,并使用 For Each 语句循环访问字典。

Private Sub IterateThroughDictionary()
    Dim elements As Dictionary(Of String, Element) = BuildDictionary()

    For Each kvp As KeyValuePair(Of String, Element) In elements
        Dim theElement As Element = kvp.Value

        Console.WriteLine("key: " & kvp.Key)
        With theElement
            Console.WriteLine("values: " & .Symbol & " " &
                .Name & " " & .AtomicNumber)
        End With
    Next
End Sub

Private Function BuildDictionary() As Dictionary(Of String, Element)
    Dim elements As New Dictionary(Of String, Element)

    AddToDictionary(elements, "K", "Potassium", 19)
    AddToDictionary(elements, "Ca", "Calcium", 20)
    AddToDictionary(elements, "Sc", "Scandium", 21)
    AddToDictionary(elements, "Ti", "Titanium", 22)

    Return elements
End Function

Private Sub AddToDictionary(ByVal elements As Dictionary(Of String, Element),
ByVal symbol As String, ByVal name As String, ByVal atomicNumber As Integer)
    Dim theElement As New Element

    theElement.Symbol = symbol
    theElement.Name = name
    theElement.AtomicNumber = atomicNumber

    elements.Add(Key:=theElement.Symbol, value:=theElement)
End Sub

Public Class Element
    Public Property Symbol As String
    Public Property Name As String
    Public Property AtomicNumber As Integer
End Class

为了使用集合初始值设定项来构建Dictionary集合,您可以将BuildDictionaryAddToDictionary方法替换为以下方法。

Private Function BuildDictionary2() As Dictionary(Of String, Element)
    Return New Dictionary(Of String, Element) From
        {
            {"K", New Element With
                {.Symbol = "K", .Name = "Potassium", .AtomicNumber = 19}},
            {"Ca", New Element With
                {.Symbol = "Ca", .Name = "Calcium", .AtomicNumber = 20}},
            {"Sc", New Element With
                {.Symbol = "Sc", .Name = "Scandium", .AtomicNumber = 21}},
            {"Ti", New Element With
                {.Symbol = "Ti", .Name = "Titanium", .AtomicNumber = 22}}
        }
End Function

以下示例使用 ContainsKey 方法和 Item[] 属性来快速通过键查找 Dictionary 项目。 通过此属性Item,可以使用 Visual Basic 中的代码访问集合elements中的elements(symbol)项。

Private Sub FindInDictionary(ByVal symbol As String)
    Dim elements As Dictionary(Of String, Element) = BuildDictionary()

    If elements.ContainsKey(symbol) = False Then
        Console.WriteLine(symbol & " not found")
    Else
        Dim theElement = elements(symbol)
        Console.WriteLine("found: " & theElement.Name)
    End If
End Sub

以下示例则使用 TryGetValue 方法按键快速查找某个项。

Private Sub FindInDictionary2(ByVal symbol As String)
    Dim elements As Dictionary(Of String, Element) = BuildDictionary()

    Dim theElement As Element = Nothing
    If elements.TryGetValue(symbol, theElement) = False Then
        Console.WriteLine(symbol & " not found")
    Else
        Console.WriteLine("found: " & theElement.Name)
    End If
End Sub

使用 LINQ 访问集合

LINQ(Language-Integrated 查询)可用于访问集合。 LINQ 查询提供筛选、排序和分组功能。 有关详细信息,请参阅 Visual Basic 中的 LINQ 入门

以下示例针对泛型 List运行 LINQ 查询。 LINQ 查询返回包含结果的不同集合。

Private Sub ShowLINQ()
    Dim elements As List(Of Element) = BuildList()

    ' LINQ Query.
    Dim subset = From theElement In elements
                  Where theElement.AtomicNumber < 22
                  Order By theElement.Name

    For Each theElement In subset
        Console.WriteLine(theElement.Name & " " & theElement.AtomicNumber)
    Next

    ' Output:
    '  Calcium 20
    '  Potassium 19
    '  Scandium 21
End Sub

Private Function BuildList() As List(Of Element)
    Return New List(Of Element) From
        {
            {New Element With
                {.Symbol = "K", .Name = "Potassium", .AtomicNumber = 19}},
            {New Element With
                {.Symbol = "Ca", .Name = "Calcium", .AtomicNumber = 20}},
            {New Element With
                {.Symbol = "Sc", .Name = "Scandium", .AtomicNumber = 21}},
            {New Element With
                {.Symbol = "Ti", .Name = "Titanium", .AtomicNumber = 22}}
        }
End Function

Public Class Element
    Public Property Symbol As String
    Public Property Name As String
    Public Property AtomicNumber As Integer
End Class

对集合进行排序

下面的示例演示了对集合进行排序的过程。 示例对存储在Car中的List<T>类实例进行排序。 该 Car 类实现 IComparable<T> 接口,这要求 CompareTo 实现该方法。

每次调用 CompareTo 该方法时,都会进行一个用于排序的比较。 方法中的 CompareTo 用户编写代码返回一个值,用于将当前对象与另一个对象进行比较。 如果当前对象小于另一个对象,则返回的值小于零,如果当前对象大于其他对象,则返回的值小于零;如果它们相等,则大于零。 这样,便可以在代码中定义大于、小于和等于的条件。

在方法中 ListCarscars.Sort() 语句对列表进行排序。 对 SortList<T> 方法的此调用将导致为 CompareTo 中的 Car 对象自动调用 List 方法。

Public Sub ListCars()

    ' Create some new cars.
    Dim cars As New List(Of Car) From
    {
        New Car With {.Name = "car1", .Color = "blue", .Speed = 20},
        New Car With {.Name = "car2", .Color = "red", .Speed = 50},
        New Car With {.Name = "car3", .Color = "green", .Speed = 10},
        New Car With {.Name = "car4", .Color = "blue", .Speed = 50},
        New Car With {.Name = "car5", .Color = "blue", .Speed = 30},
        New Car With {.Name = "car6", .Color = "red", .Speed = 60},
        New Car With {.Name = "car7", .Color = "green", .Speed = 50}
    }

    ' Sort the cars by color alphabetically, and then by speed
    ' in descending order.
    cars.Sort()

    ' View all of the cars.
    For Each thisCar As Car In cars
        Console.Write(thisCar.Color.PadRight(5) & " ")
        Console.Write(thisCar.Speed.ToString & " ")
        Console.Write(thisCar.Name)
        Console.WriteLine()
    Next

    ' Output:
    '  blue  50 car4
    '  blue  30 car5
    '  blue  20 car1
    '  green 50 car7
    '  green 10 car3
    '  red   60 car6
    '  red   50 car2
End Sub

Public Class Car
    Implements IComparable(Of Car)

    Public Property Name As String
    Public Property Speed As Integer
    Public Property Color As String

    Public Function CompareTo(ByVal other As Car) As Integer _
        Implements System.IComparable(Of Car).CompareTo
        ' A call to this method makes a single comparison that is
        ' used for sorting.

        ' Determine the relative order of the objects being compared.
        ' Sort by color alphabetically, and then by speed in
        ' descending order.

        ' Compare the colors.
        Dim compare As Integer
        compare = String.Compare(Me.Color, other.Color, True)

        ' If the colors are the same, compare the speeds.
        If compare = 0 Then
            compare = Me.Speed.CompareTo(other.Speed)

            ' Use descending order for speed.
            compare = -compare
        End If

        Return compare
    End Function
End Class

定义自定义集合

可以通过实现 IEnumerable<T>IEnumerable 接口来定义集合。 有关详细信息,请参阅 枚举集合

虽然可以定义自定义集合,但通常最好改用 .NET Framework 中包含的集合,本主题前面在 “集合类型 ”中对此进行介绍。

以下示例定义名为 的自定义集合类。 此类实现 IEnumerable 接口,此操作需要实现 GetEnumerator 方法。

该方法 GetEnumerator 返回类的 ColorEnumerator 实例。 ColorEnumerator实现了IEnumerator接口,这要求必须实现Current属性、MoveNext方法和Reset方法。

Public Sub ListColors()
    Dim colors As New AllColors()

    For Each theColor As Color In colors
        Console.Write(theColor.Name & " ")
    Next
    Console.WriteLine()
    ' Output: red blue green
End Sub

' Collection class.
Public Class AllColors
    Implements System.Collections.IEnumerable

    Private _colors() As Color =
    {
        New Color With {.Name = "red"},
        New Color With {.Name = "blue"},
        New Color With {.Name = "green"}
    }

    Public Function GetEnumerator() As System.Collections.IEnumerator _
        Implements System.Collections.IEnumerable.GetEnumerator

        Return New ColorEnumerator(_colors)

        ' Instead of creating a custom enumerator, you could
        ' use the GetEnumerator of the array.
        'Return _colors.GetEnumerator
    End Function

    ' Custom enumerator.
    Private Class ColorEnumerator
        Implements System.Collections.IEnumerator

        Private _colors() As Color
        Private _position As Integer = -1

        Public Sub New(ByVal colors() As Color)
            _colors = colors
        End Sub

        Public ReadOnly Property Current() As Object _
            Implements System.Collections.IEnumerator.Current
            Get
                Return _colors(_position)
            End Get
        End Property

        Public Function MoveNext() As Boolean _
            Implements System.Collections.IEnumerator.MoveNext
            _position += 1
            Return (_position < _colors.Length)
        End Function

        Public Sub Reset() Implements System.Collections.IEnumerator.Reset
            _position = -1
        End Sub
    End Class
End Class

' Element class.
Public Class Color
    Public Property Name As String
End Class

迭代器

迭代器用于对集合执行自定义迭代。 迭代器可以是方法或 get 访问器。 迭代器使用 Yield 语句一次返回集合的每个元素。

使用 For Each…Next 语句调用迭代器。 循环的每个 For Each 迭代都会调用迭代器。 在迭代器中达到Yield语句时,将会返回一个表达式,并保留代码的当前位置。 下次调用迭代器时,将从该位置重启执行。

有关详细信息,请参阅迭代器(Visual Basic)。

以下示例使用迭代器方法。 迭代器方法中有一个语句,该语句位于Yield循环内部。 在 ListEvenNumbers 方法中,For Each 语句体的每次迭代都会调用迭代器方法,该方法会推动到下一个 Yield 语句。

Public Sub ListEvenNumbers()
    For Each number As Integer In EvenSequence(5, 18)
        Console.Write(number & " ")
    Next
    Console.WriteLine()
    ' Output: 6 8 10 12 14 16 18
End Sub

Private Iterator Function EvenSequence(
ByVal firstNumber As Integer, ByVal lastNumber As Integer) _
As IEnumerable(Of Integer)

' Yield even numbers in the range.
    For number = firstNumber To lastNumber
        If number Mod 2 = 0 Then
            Yield number
        End If
    Next
End Function

另请参阅