集合(C# 和 Visual Basic)

对于很多应用程序,需要创建和管理相关对象组。 有两种方式可以将对象分组:创建对象数组以及创建对象集合。

数组用于创建和最有用的强类型对象。固定数量。 有关数组的信息,请参见 数组 (Visual Basic)数组(C# 编程指南)

集合提供一种更灵活的方式使用对象组。 与数组不同,处理的对象组可根据程序更改的需要动态地增长和收缩。 对于某些集合,您可以指定键到使用键,则放入集合中的所有对象,以便可以快速检索对象。

集合是类,因此必须声明新集合后,才能向该集合中添加元素。

如果集合仅包含数据类型的组件,则在 System.Collections.Generic 可以使用命名空间中的一选件类。 “泛型”集合强制“类型安全”,因此无法向该集合中添加任何其他数据类型。 从泛型集合中检索元素时,不必确定元素的数据类型或转换它。

备注

对于本主题中的示例,请包括 导入 语句 (Visual Basic) 或 使用 指令 (c#) System.Collections.GenericSystem.Linq 命名空间。

主题内容

  • 使用简单集合

  • 类型的集合

    • System.Collections.Generic 选件类

    • System.Collections.Concurrent 选件类

    • System.Collections 类

    • Visual Basic 集合选件类

  • 实现键/值对集合

  • 使用访问的 LINQ 集合

  • 排序集合

  • 定义自定义集合

  • 迭代器

使用简单集合

本节中的示例使用泛型 List<T> 选件类,允许您使用强类型一起使用列表对象。

使用 对于每个 for each…next (Visual Basic) 或 foreach (c#) 语句,下面的示例生成字符串列表传递字符串然后重复。

' 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.
var salmons = new List<string>();
salmons.Add("chinook");
salmons.Add("coho");
salmons.Add("pink");
salmons.Add("sockeye");

// Iterate through the list.
foreach (var salmon in salmons)
{
    Console.Write(salmon + " ");
}
// Output: chinook coho pink sockeye

如果集合的内容事先知道,可以使用集合初始值设定项初始化集合。 有关更多信息,请参见集合初始值设定项 (Visual Basic)对象和集合初始值设定项(C# 编程指南)

下面的示例与前面的示例,除此之外,集合初始值设定项用于将元素添加到集合中。

' 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
// Create a list of strings by using a
// collection initializer.
var salmons = new List<string> { "chinook", "coho", "pink", "sockeye" };

// Iterate through the list.
foreach (var salmon in salmons)
{
    Console.Write(salmon + " ");
}
// Output: chinook coho pink sockeye

可以使用 for…next (Visual Basic) 或 (c#) 语句而不是 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.
var salmons = new List<string> { "chinook", "coho", "pink", "sockeye" };

for (var index = 0; index < salmons.Count; index++)
{
    Console.Write(salmons[index] + " ");
}
// 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
// Create a list of strings by using a
// collection initializer.
var salmons = new List<string> { "chinook", "coho", "pink", "sockeye" };

// Remove an element from the list by specifying
// the object.
salmons.Remove("coho");

// Iterate through the list.
foreach (var salmon in salmons)
{
    Console.Write(salmon + " ");
}
// Output: chinook pink sockeye

下面的示例从泛型移除元素的列表。 而不是 For Each 语句,按降序重复使用的 for…next (Visual Basic) 或 (c#) 语句。 这是因为,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
var numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// Remove odd numbers.
for (var index = numbers.Count - 1; index >= 0; index--)
{
    if (numbers[index] % 2 == 1)
    {
        // Remove the element by specifying
        // the zero-based index in the list.
        numbers.RemoveAt(index);
    }
}

// Iterate through the list.
// A lambda expression is placed in the ForEach method
// of the List(T) object.
numbers.ForEach(
    number => Console.Write(number + " "));
// Output: 0 2 4 6 8

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

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
private void IterateThroughList()
{
    var theGalaxies = new List<Galaxy>
        {
            new Galaxy() { Name="Tadpole", MegaLightYears=400},
            new Galaxy() { Name="Pinwheel", MegaLightYears=25},
            new Galaxy() { Name="Milky Way", MegaLightYears=0},
            new Galaxy() { Name="Andromeda", MegaLightYears=3}
        };

    foreach (Galaxy theGalaxy in theGalaxies)
    {
        Console.WriteLine(theGalaxy.Name + "  " + theGalaxy.MegaLightYears);
    }

    // Output:
    //  Tadpole  400
    //  Pinwheel  25
    //  Milky Way  0
    //  Andromeda  3
}

public class Galaxy
{
    public string Name { get; set; }
    public int MegaLightYears { get; set; }
}

类型的集合

.NET framework 提供了许多常见集合。 集合中的每种类型为特定目的而设计。

集合选件类的以下组本节中所述:

  • System.Collections.Generic 选件类

  • System.Collections.Concurrent 选件类

  • System.Collections 选件类

  • Visual Basic Collection 选件类

ybcx56wz.collapse_all(zh-cn,VS.110).gifSystem.Collections.Generic 选件类

可以创建泛型集合通过使用一选件类在 System.Collections.Generic 命名空间。 当泛型集合中的所有项具有相同的数据类型时,泛型集合很有用。 泛型集合通过仅允许所需的数据类型添加强制转换为强类型。

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

描述

[ T:System.Collections.Generic.Dictionary`2 ]

表示根据键进行组织的键/值对的集合。

[ T:System.Collections.Generic.List`1 ]

表示可以按索引获取对象的列表。 提供了搜索,排序,并修改列表。

[ T:System.Collections.Generic.Queue`1 ]

表示第一,对象的第一 (FIFO) 集合。

[ T:System.Collections.Generic.SortedList`2 ]

表示根据键进行排序的键/值对的集合,而键基于的是相关的 IComparer<T> 实现。

[ T:System.Collections.Generic.Stack`1 ]

表示最后,对象的第一 (LIFO) 集合。

有关附加信息,请参见 常用的集合类型选择集合类System.Collections.Generic

ybcx56wz.collapse_all(zh-cn,VS.110).gifSystem.Collections.Concurrent 选件类

在 .NET framework 4 中,在 System.Collections.Concurrent 空间中的集合为从多个线程访问集合项提供有效的线程安全操作。

应使用在 System.Collections.Concurrent 命名空间的选件类而不是相应类型 System.Collections.GenericSystem.Collections 命名空间,每当多个线程同时访问集合。 有关更多信息,请参见线程安全集合System.Collections.Concurrent

有些类包括在 System.Collections.Concurrent 命名空间是 BlockingCollection<T>ConcurrentDictionary<TKey, TValue>ConcurrentQueue<T>ConcurrentStack<T>

ybcx56wz.collapse_all(zh-cn,VS.110).gifSystem.Collections 类

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

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

下表列出了一些在 System.Collections 命名空间的常用选件类:

描述

[ T:System.Collections.ArrayList ]

表示动态增加根据要求大小的数组对象。

[ T:System.Collections.Hashtable ]

表示根据键的哈希代码进行组织的键/值对的集合。

[ T:System.Collections.Queue ]

表示第一,对象的第一 (FIFO) 集合。

[ T:System.Collections.Stack ]

表示最后,对象的第一 (LIFO) 集合。

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

ybcx56wz.collapse_all(zh-cn,VS.110).gifVisual Basic 集合选件类

使用数值索引或 String 键,可以使用 Visual Basic Collection 选件类访问集合项。 可以将项添加到集合对象要么具有或不指定键。 如果添加一个没有键的项,则必须使用其数值索引才能访问它。

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 选件类实现为哈希表,检索使用其键的值快。

使用 For Each 语句,下面的示例创建 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)

    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
private void IterateThruDictionary()
{
    Dictionary<string, Element> elements = BuildDictionary();

    foreach (KeyValuePair<string, Element> kvp in elements)
    {
        Element theElement = kvp.Value;

        Console.WriteLine("key: " + kvp.Key);
        Console.WriteLine("values: " + theElement.Symbol + " " +
            theElement.Name + " " + theElement.AtomicNumber);
    }
}

private Dictionary<string, Element> BuildDictionary()
{
    var elements = new Dictionary<string, Element>();

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

    return elements;
}

private void AddToDictionary(Dictionary<string, Element> elements,
    string symbol, string name, int atomicNumber)
{
    Element theElement = new Element();

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

    elements.Add(key: theElement.Symbol, value: theElement);
}

public class Element
{
    public string Symbol { get; set; }
    public string Name { get; set; }
    public int AtomicNumber { get; set; }
}

使用集合初始值设定项生成 Dictionary 集合,您可以使用下面的方法替换 BuildDictionary 和 AddToDictionary 方法。

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 Dictionary<string, Element> BuildDictionary2()
{
    return new Dictionary<string, Element>
    {
        {"K",
            new Element() { Symbol="K", Name="Potassium", AtomicNumber=19}},
        {"Ca",
            new Element() { Symbol="Ca", Name="Calcium", AtomicNumber=20}},
        {"Sc",
            new Element() { Symbol="Sc", Name="Scandium", AtomicNumber=21}},
        {"Ti",
            new Element() { Symbol="Ti", Name="Titanium", AtomicNumber=22}}
    };
}

下面的示例使用 ContainsKey 方法和 DictionaryItem 属性由键快速查找项。 使用 Visual Basic,的 elements(symbol) 代码 Item 特性以在 C# 中可以访问在 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
private void FindInDictionary(string symbol)
{
    Dictionary<string, Element> elements = BuildDictionary();

    if (elements.ContainsKey(symbol) == false)
    {
        Console.WriteLine(symbol + " not found");
    }
    else
    {
        Element theElement = elements[symbol];
        Console.WriteLine("found: " + theElement.Name);
    }
}

下面的示例使用 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
private void FindInDictionary2(string symbol)
{
    Dictionary<string, Element> elements = BuildDictionary();

    Element theElement = null;
    if (elements.TryGetValue(symbol, out theElement) == false)
        Console.WriteLine(symbol + " not found");
    else
        Console.WriteLine("found: " + theElement.Name);
}

使用访问的 LINQ 集合

LINQ (语言集成查询) 来访问集合。 LINQ 查询,提供筛选、排序和分组功能。 有关更多信息,请参见Visual Basic 中的 LINQ 入门C# 中的 LINQ 入门

下面的示例执行 LINQ 查询泛型 List。 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
private void ShowLINQ()
{
    List<Element> elements = BuildList();

    // LINQ Query.
    var subset = from theElement in elements
                 where theElement.AtomicNumber < 22
                 orderby theElement.Name
                 select theElement;

    foreach (Element theElement in subset)
    {
        Console.WriteLine(theElement.Name + " " + theElement.AtomicNumber);
    }

    // Output:
    //  Calcium 20
    //  Potassium 19
    //  Scandium 21
}

private List<Element> BuildList()
{
    return new List<Element>
    {
        { new Element() { Symbol="K", Name="Potassium", AtomicNumber=19}},
        { new Element() { Symbol="Ca", Name="Calcium", AtomicNumber=20}},
        { new Element() { Symbol="Sc", Name="Scandium", AtomicNumber=21}},
        { new Element() { Symbol="Ti", Name="Titanium", AtomicNumber=22}}
    };
}

public class Element
{
    public string Symbol { get; set; }
    public string Name { get; set; }
    public int AtomicNumber { get; set; }
}

排序集合

下面的示例演示排序的集合的方法。 该示例对 List<T>存储 Car 选件类的实例。 Car 选件类实现 IComparable<T> 接口,需要 CompareTo 方法执行。

每个调用 CompareTo 方法使用于排序的唯一比较。 在 CompareTo 方法的用户编写的代码将当前对象的每个比较的值与其他对象的。 返回的值小于零,如果当前对象与另一个对象小于,大于零,如果当前对象大于另一个对象和零,则它们相等。 这使您可以定义代码大的标准相比,比和相等。

在 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.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
private void ListCars()
{
    var cars = new List<Car>
    {
        { new Car() { Name = "car1", Color = "blue", Speed = 20}},
        { new Car() { Name = "car2", Color = "red", Speed = 50}},
        { new Car() { Name = "car3", Color = "green", Speed = 10}},
        { new Car() { Name = "car4", Color = "blue", Speed = 50}},
        { new Car() { Name = "car5", Color = "blue", Speed = 30}},
        { new Car() { Name = "car6", Color = "red", Speed = 60}},
        { new Car() { 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.
    foreach (Car thisCar in cars)
    {
        Console.Write(thisCar.Color.PadRight(5) + " ");
        Console.Write(thisCar.Speed.ToString() + " ");
        Console.Write(thisCar.Name);
        Console.WriteLine();
    }

    // Output:
    //  blue  50 car4
    //  blue  30 car5
    //  blue  20 car1
    //  green 50 car7
    //  green 10 car3
    //  red   60 car6
    //  red   50 car2
}

public class Car : IComparable<Car>
{
    public string Name { get; set; }
    public int Speed { get; set; }
    public string Color { get; set; }

    public int CompareTo(Car other)
    {
        // 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.
        int compare;
        compare = String.Compare(this.Color, other.Color, true);

        // If the colors are the same, compare the speeds.
        if (compare == 0)
        {
            compare = this.Speed.CompareTo(other.Speed);

            // Use descending order for speed.
            compare = -compare;
        }

        return compare;
    }
}

定义自定义集合

通过实现 IEnumerable<T>IEnumerable 接口定义集合。 有关其他信息,请参见 枚举集合如何:使用 foreach 访问集合类(C# 编程指南)

虽然可以定义自定义集合,使用在 .NET framework 中,在 Kinds of Collections 将本主题前面描述的集合通常最好。

下面的示例定义名为 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
private void ListColors()
{
    var colors = new AllColors();

    foreach (Color theColor in colors)
    {
        Console.Write(theColor.Name + " ");
    }
    Console.WriteLine();
    // Output: red blue green
}


// Collection class.
public class AllColors : System.Collections.IEnumerable
{
    Color[] _colors =
    {
        new Color() { Name = "red" },
        new Color() { Name = "blue" },
        new Color() { Name = "green" }
    };

    public System.Collections.IEnumerator GetEnumerator()
    {
        return new ColorEnumerator(_colors);

        // Instead of creating a custom enumerator, you could
        // use the GetEnumerator of the array.
        //return _colors.GetEnumerator();
    }

    // Custom enumerator.
    private class ColorEnumerator : System.Collections.IEnumerator
    {
        private Color[] _colors;
        private int _position = -1;

        public ColorEnumerator(Color[] colors)
        {
            _colors = colors;
        }

        object System.Collections.IEnumerator.Current
        {
            get
            {
                return _colors[_position];
            }
        }

        bool System.Collections.IEnumerator.MoveNext()
        {
            _position++;
            return (_position < _colors.Length);
        }

        void System.Collections.IEnumerator.Reset()
        {
            _position = -1;
        }
    }
}

// Element class.
public class Color
{
    public string Name { get; set; }
}

迭代器

迭代器 用于对集合的自定义迭代。 迭代器可以是方法或 get 访问器。 迭代器使用一个 Yield (Visual Basic) 或 将返回 (c#) 语句返回集合中的每个元素一个节点。

使用 对于每个 for each…next (Visual Basic) 或 foreach (c#) 语句,则调用迭代器。 For Each 循环的每次迭代调用迭代器。 当 Yield 或 yield return 语句在迭代器时为止,表达式将返回,并且,代码的当前位置保留。 执行从该位置下次重新启动迭代器调用。

有关更多信息,请参见迭代器(C# 和 Visual Basic)

下面的示例使用一个迭代器方法。 迭代器方法具有在 for…next 的一个 Yield 或 yield return 语句 (Visual Basic) 或 (c#) 循环内。 在 ListEvenNumbers 方法,For Each 语句体的每个迭代创建对迭代器方法,执行下一 Yield 或 yield return 语句。

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
private void ListEvenNumbers()
{
    foreach (int number in EvenSequence(5, 18))
    {
        Console.Write(number.ToString() + " ");
    }
    Console.WriteLine();
    // Output: 6 8 10 12 14 16 18
}

private static IEnumerable<int> EvenSequence(
    int firstNumber, int lastNumber)
{
    // Yield even numbers in the range.
    for (var number = firstNumber; number <= lastNumber; number++)
    {
        if (number % 2 == 0)
        {
            yield return number;
        }
    }
}

请参见

任务

如何:使用 foreach 访问集合类(C# 编程指南)

参考

对象和集合初始值设定项(C# 编程指南)

Option Strict 语句

概念

集合初始值设定项 (Visual Basic)

LINQ to Objects

并行 LINQ (PLINQ)

选择集合类

集合内的比较和排序

何时使用泛型集合

其他资源

集合最优方法

编程概念

集合和数据结构

创建和操作集合