共用方式為


集合 (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 一些常用類別:

班級 說明
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.Generic 命名空間中的System.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 一些常用類別:

班級 說明
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 Query) 可用來存取集合。 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 使用者撰寫的程式代碼會針對目前物件與另一個物件的每個比較傳回值。 如果目前物件小於其他物件,則傳回的值小於零,如果目前物件大於其他物件,則大於零;如果物件相等則為零。 這可讓您在程式代碼中定義大於、小於和等於的準則。

ListCars方法中,cars.Sort()語句用來排序列表。 這個對 Sort 方法的 List<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 中包含的集合,如本主題稍早的集合 種類 中所述。

下列範例會定義名為的 AllColors自定義集合類別。 這個類別實作了 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語句被觸及時,會返回一個表達式,並保留程式碼中的目前位置。 下次呼叫反覆運算器時,會從該位置重新啟動執行。

如需詳細資訊,請參閱 Iterators (Visual Basic)

下列範例使用反覆運算器方法。 反覆運算器方法在 YieldFor...Next 迴圈內有一個語句。 在 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

另請參閱