Udostępnij przez


Kolekcje (C# i Visual Basic)

W przypadku wielu aplikacji możesz chcieć utworzyć grupy powiązanych obiektów i zarządzać nimi.Istnieją dwa sposoby grupowania obiektów: poprzez tworzenie tablic obiektów oraz poprzez tworzenie kolekcji obiektów.

Tablice są najbardziej przydatne do tworzenia i pracy ze stałą liczbą jednoznacznie silnych obiektów.Informacje na temat tablic – zobacz: Tablice w Visual Basic lub Tablice (Przewodnik programowania w języku C#).

Kolekcje zapewniają bardziej elastyczny sposób pracy z grupami obiektów.W odróżnieniu od tablic, grupa obiektów, z którymi pracujesz może rosnąć i maleć dynamicznie, wraz ze zmianami zapotrzebowań aplikacji.W niektórych kolekcjach można przypisać klawisz do dowolnych obiektów umieszczonych do kolekcji, co pozwala na szybkie pobranie obiektu przy użyciu klucza.

Kolekcja jest klasą, więc należy zadeklarować nową kolekcję, zanim będzie można dodać elementy do kolekcji.

Jeśli kolekcja zawiera elementy tylko jednego typu danych, można użyć jednej z klas w obszarze nazw System.Collections.Generic.Ogólna kolekcja wymusza typ bezpieczeństwa tak, że można do niej dodać inny typ danych.Kiedy odzyskujesz element z kolekcji generycznej, nie musisz określać jego typu danych, ani go konwertować.

[!UWAGA]

Przykłady w tym temacie zawierają instrukcje Import (Visual Basic) lub dyrektywy Using (C#) dla przestrzeni nazw System.Collections.Generic i System.Linq.

W tym temacie

  • Korzystanie z prostej kolekcji

  • Rodzaje kolekcji

    • Klasy System.Collections.Generic

    • Klasy System.Collections.Concurrent

    • Klasy System.Collections

    • Klasa kolekcji Visual Basic

  • Implementacja par kluczy/wartości kolekcji

  • Korzystanie z LINQ, aby uzyskać dostęp do kolekcji

  • Sortowanie kolekcji

  • Definiowanie kolekcji niestandardowej

  • Iteratory

Za pomocą prostej kolekcji

Przykłady w tej sekcji używają ogólnej klasy List , która umożliwia pracę z listami obiektów o jednoznacznie określonej klasie.

Poniższy przykład tworzy listę ciągów i następnie iterację przez ciągi przy użyciu instrukcji For Each…Next (Visual Basic) lub 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

Jeśli zawartość kolekcji jest znana z wyprzedzeniem, można użyć inicjatora kolekcji do zainicjowania kolekcji.Aby uzyskać więcej informacji, zobacz Inicjatory kolekcji (Visual Basic) lub Inicjatory obiektów i kolekcji (Przewodnik programowania w języku C#).

Poniższy przykład jest taka sam, jak poprzedni, z wyjątkiem tego, że inicjator kolekcji służy do dodawania elementów do kolekcji.

' 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

Można użyć instrukcji For…Next (Visual Basic) lub dla (C#) zamiast instrukcji For Each, aby przechodzić kolejno przez elementy kolekcjiOsiągniesz to uzyskując dostęp do elementów kolekcji przez pozycję indeksu.Indeks elementów zaczyna się od 0 i kończy się liczbą elementów pomniejszoną o 1.

Poniższy przykład wykonuje iterację przez elementy kolekcji za pomocą For…Next zamiast 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

Poniższy przykład usuwa element z kolekcji określając obiekt, który należy usunąć.

' 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

Poniższy przykład usuwa elementy z listy ogólnej.Zamiast instrukcji For Each, instrukcja Dla…Dalej (Visual Basic) lub dla jest używana, która dokonuje iteracji w kolejności malejącej.Jest tak, ponieważ metoda RemoveAt powoduje, że elementy po usuniętym elemencie muszą mieć niższą wartość indeksu.

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

Dla typu elementów w List można również definiować własne klasy.W poniższym przykładzie klasa Galaxy, która jest używana przez List jest zdefiniowana w kodzie.

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; }
}

Rodzaje kolekcji

Wiele typowych kolekcji jest dostarczanych przez.NET Framework.Każdy typu kolekcji jest przeznaczony do określonego celu.

W tej sekcji opisano następujące grupy klas kolekcji:

  • System.Collections.Generic klasy

  • System.Collections.Concurrent klasy

  • System.Collections klasy

  • Klasa Visual Basic Collection

Klasy System.Collections.Generic

Możesz utworzyć ogólną kolekcję używając jednej z klas w przestrzeni nazwy System.Collections.Generic.Ogólna kolekcja jest przydatna, gdy każdy element w kolekcji ma ten sam typ danych.Ogólna kolekcja wymusza silne wpisywanie, zezwalając tylko na żądane dane typu, który ma być dodany.

Poniższa lista zawiera niektóre z najczęściej używanych klas w obszarze nazw System.Collections.Generic:

Klasa

Opis

Dictionary

Przedstawia kolekcję par kluczy/wartości, które są zorganizowane na podstawie klucza.

List

Przedstawia listę obiektów, które mogą być udostępniane przez indeks.Oferuje metody wyszukiwania, sortowania i modyfikowania list.

Queue

Przedstawia kolekcję FIFO („pierwszy na wejściu, pierwszy na wyjściu”) obiektów.

SortedList

Przedstawia kolekcję par kluczy/wartości, które są klasyfikowane według klucza w oparciu o związaną implementację IComparer.

Stack

Przedstawia kolekcję LIFO („ostatni na wejściu, pierwszy na wyjściu”) obiektów.

Aby uzyskać więcej informacji, zobacz Często używane typy kolekcji, Wybieranie klasy kolekcji, and System.Collections.Generic.

Klasy System.Collections.Concurrent

W .NET Framework 4, kolekcje w nazwie przestrzeni System.Collections.Concurrent zapewniają efektywne działania wątków do uzyskiwania dostępu do elementów kolekcji z wielu wątków.

Klasy w obszarze nazw System.Collections.Concurrent powinny być używane zamiast odpowiednich typów w System.Collections.Generic i obszarów nazw System.Collections, gdy wiele wątków uzyskuje dostęp do kolekcji jednocześnie.Aby uzyskać więcej informacji, zobacz Kolekcje bezpieczne wątkowo i System.Collections.Concurrent.

Niektóre klasy uwzględnione w przestrzeni nazw System.Collections.Concurrent to BlockingCollection, ConcurrentDictionary, ConcurrentQueue oraz ConcurrentStack.

Klasy System.Collections

Klas w obszarze nazw System.Collections nie przechowują elementów jako specjalnie typowanych obiektów, ale jako obiekty typu Object.

Kiedy to tylko możliwe, należy używać ogólnych kolekcji w przestrzeni nazwy System.Collections.Generic lub przestrzeni nazwy System.Collections.Concurrent zamiast typów odziedziczonych w przestrzeni nazwy System.Collections.

Poniższa lista zawiera niektóre z najczęściej używanych klas w obszarze nazw System.Collections:

Klasa

Opis

ArrayList

Przedstawia tablicę obiektów, których rozmiar jest dynamicznie zwiększany w miarę potrzeb.

Hashtable

Przedstawia kolekcję par kluczy/wartości, które są zorganizowane na podstawie kodu mieszanego klucza.

Queue

Przedstawia kolekcję FIFO („pierwszy na wejściu, pierwszy na wyjściu”) obiektów.

Stack

Przedstawia kolekcję LIFO („ostatni na wejściu, pierwszy na wyjściu”) obiektów.

Przestrzeń nazw System.Collections.Specialized zawiera kolekcję klas wyspecjalizowanych i o wyraźnie określonym typie, jak kolekcje wyłącznie ciągów, listy powiązane i słowniki hybrydowe.

Klasa kolekcji Visual Basic

Można użyć klasy Visual Basic Collection do uzyskania dostępu do elementu kolekcji, korzystając albo z indeksu numerycznego albo klucza String.Możesz dodawać elementy do obiektu kolekcji z określeniem lub bez określenia klucza.Jeśli dodajesz element bez klucza, musisz użyć jego indeksu liczbowego, aby uzyskać do niego dostęp.

Klasa Visual Basic Collection przechowuje wszystkie elementy jako typy Object, więc można dodać element każdego typu danych.Nie ma zabezpieczenia przez dodawaniem nieprawidłowych typów danych.

Kiedy używasz klasy Visual Basic Collection, pierwszy element kolekcji posiada indeks 1.Różni się to od klas kolekcji .NET Framework, dla których indeks początkowy to 0.

Kiedy to tylko możliwe, należy używać ogólnych kolekcji w przestrzeni nazwy System.Collections.Generic lub przestrzeni nazwy System.Collections.Concurrent zamiast klasy Visual Basic Collection.

Aby uzyskać więcej informacji, zobacz Collection.

Implementacja par kluczy/wartości kolekcji

Generyczna kolekcja Dictionary umożliwia dostęp do elementów w kolekcji za pomocą klucza każdego elementu.Każdy dodatkem do słownika składa się z wartości i skojarzonego z nią klucza.Pobieranie wartości przy użyciu własnego klucza jest szybkie ponieważ klasa Dictionary jest implementowana jako tablica wartości funkcji mieszającej.

Poniższy przykład tworzy kolekcję Dictionary i wykonuje iteracje przez słownik za pomocą instrukcji 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
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; }
}

Aby użyć w zamian inicjalizatora kolekcji, aby skompilować kolekcję Dictionary możesz zastąpić metody BuildDictionary i AddToDictionary poniższą metodą..

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}}
    };
}

W poniższym przykładzie użyto metody ContainsKey i właściwości Item property of Dictionary pozwalających szybko znaleźć element według klucza..Właściwość Item umożliwia dostęp do elementu w kodzie elements kolekcji za pomocą elements(symbol) w języku Visual Basic lub elements[symbol] w języku C#.

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);
    }
}

W poniższym przykładzie zamiast użyto metody TryGetValue pozwalającej szybko znaleźć element według klucza.

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);
}

Za pomocą LINQ do dostępu do kolekcji

LINQ (Language-Integrated Query) może służyć do uzyskiwania dostępu do kolekcji.Zapytania LINQ zapewniają filtrowanie, porządkowanie i możliwości grupowania.Aby uzyskać więcej informacji, zobacz Wprowadzenie do programu LINQ w Visual Basic lub Wprowadzenie do korzystania z LINQ w C#.

Poniższy przykład wykonuje zapytanie LINQ na ogólnej List.Zapytanie LINQ zwraca inną kolekcję, która zawiera wyniki.

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; }
}

Sortowanie kolekcji

Poniżej przedstawiono przykładową procedurę sortowania zbioru.Przykład sortuje wystąpienia Car klasy, które są przechowywane w List.Klasa Car implementuje IComparable interfejs, który wymaga, aby metoda CompareTo była realizowana.

Każde wywołanie CompareTo metody tworzy pojedyncze porównanie, który jest używane do sortowania.Kod napisany przez użytkownika w metodzie CompareTo wraca wartość dla każdego porównania bieżącego obiektu z innym obiektem.Zwrócona wartość jest mniejsza niż zero, jeżeli bieżący obiekt jest mniejszy niż inny obiekt, większa niż zero, jeżeli bieżący obiekt jest większy niż inny obiekt, oraz zero, jeżeli są równe.Umożliwia to definiowanie w kodzie kryteriów dla większych niż, mniejszych niż i równych.

W metodzie ListCars instrukcja cars.Sort() sortuje listy.To wywołanie metody Sort z List powoduje, że metoda CompareTo zostaje wywołana automatycznie dla obiektów Car w 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
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;
    }
}

Definiowanie kolekcji niestandardowej

Możesz zdefiniować kolekcję implementując interfejs IEnumerable lub IEnumerable.Aby uzyskać więcej informacji, zobacz Wyliczanie kolekcji, Porady: uzyskiwanie dostępu do klasy kolekcji za pomocą instrukcji foreach (Przewodnik programowania w języku C#), and .

Chociaż można zdefiniować kolekcję niestandardową, to zazwyczaj lepiej jest użyć zamiast tego kolekcje, które są zawarte w.NET Framework, które są opisane w Typy kolekcji wcześniej w tym temacie.

W poniższym przykładzie zdefiniowano klasę kolekcji niestandardowej o nazwie AllColors.Ta klasa implementuje interfejs IEnumerable który wymaga, żeby metoda GetEnumerator została implementowana.

Metoda GetEnumerator zwraca wystąpienie klasy ColorEnumerator.ColorEnumerator implementuje IEnumerator interfejs, który wymaga, żeby Current pwłaściwośc, MoveNext metoda i Reset metoda była wdrożona.

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; }
}

Iteratory

iterator jest używany do wykonywania niestandardowych iteracji w kolekcji.Iteracją może być metodą lub get akcesor.Używa iteratora Zwrot (Visual Basic) lub zwróceniu przekazu (C#) instrukcja zwraca każdy element kolekcji naraz.

Wywołujesz iterację używając Dla każdego…Następny (Visual Basic) lub instrukcję dla każdego (C#).Każda iteracja For Each pętli wywołuje iteratora.Po osiągnięciu Yield lub yield return instrukcji w iteratorze, wyrażenie jest zwracane, a bieżąca lokalizacja w kodzie jest zachowywana.Wykonanie jest uruchamiane ponownie z tej lokalizacji przy następnym wywołaniu iteratora.

Aby uzyskać więcej informacji, zobacz Iteratory (C# i Visual Basic).

Poniższy przykład wykorzystuje metodę iteratora.Metoda iteratora ma Yield lub yield return instrukcji, która znajduje się wewnątrz pętli For…Next (Visual Basic) lub for (C#).W metodzie ListEvenNumbers każda iteracja instrukcji For Each tworzy wywołanie metody iteracyjnej, która przechodzi do następnej instrukcji Yield lub 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;
        }
    }
}

Zobacz też

Zadania

Porady: uzyskiwanie dostępu do klasy kolekcji za pomocą instrukcji foreach (Przewodnik programowania w języku C#)

Informacje

Inicjatory obiektów i kolekcji (Przewodnik programowania w języku C#)

Option Strict — Instrukcja

Koncepcje

Inicjatory kolekcji (Visual Basic)

LINQ do obiektów

Równoległe LINQ (PLINQ)

Wybieranie klasy kolekcji

Porównywanie i sortowanie w kolekcjach

Kiedy należy używać kolekcji ogólnych

Inne zasoby

Najlepsze praktyki kolekcji

Koncepcje programowania

Kolekcje i struktury danych

Tworzenie kolekcji i manipulowanie nimi