# 集合 (Visual Basic)

## 使用简单集合

' Create a list of strings.
Dim salmons As New List(Of String)

' 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


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


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


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:
'  Pinwheel  25
'  Milky Way  0
'  Andromeda  3
End Sub

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


## 集合的类型

• Visual Basic Collection

### System.Collections.Generic 类

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

### System.Collections 类

System.Collections 命名空间中的类不会将元素作为特别类型化的对象存储，而是作为 Object 类型的对象存储。

ArrayList 表示对象的数组，这些对象的大小会根据需要动态增加。
Hashtable 表示根据键的哈希代码进行组织的键/值对的集合。
Queue 表示对象的先进先出 (FIFO) 集合。
Stack 表示对象的后进先出 (LIFO) 集合。

System.Collections.Specialized 命名空间提供专门类型化以及强类型化的集合类，例如只包含字符串的集合以及链接列表和混合字典。

### Visual Basic 集合类

Visual Basic Collection 类将其所有元素存储为 Object 类型，因此你可以添加任何数据类型的项。 没有任何保护措施来防止添加不适当的数据类型。

## 实现键/值对集合

Dictionary<TKey,TValue> 泛型集合可通过每个元素的键访问集合中的元素。 每次对字典的添加都包含一个值和与其关联的键。 通过使用键来检索值十分快捷，因为 Dictionary 类实现为哈希表。

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)

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

End Sub

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


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


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

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


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
Else
Console.WriteLine("found: " & theElement.Name)
End If
End Sub


## 使用 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


## 对集合排序

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

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.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


## 定义自定义集合

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


## 迭代器

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