컬렉션(C# 및 Visual Basic)

많은 응용 프로그램에서 사용자는 관련된 개체의 그룹을 만들어 관리하려고 합니다. 개체의 배열을 만들거나 개체의 컬렉션을 만들어 개체를 그룹화할 수 있습니다.

배열은 강력한 형식의 개체를 고정된 수만큼 만들고 이러한 개체로 작업할 때 상당히 유용합니다. 배열에 대한 자세한 내용은 Visual Basic의 배열 또는 배열(C# 프로그래밍 가이드)을 참조하십시오.

컬렉션을 사용하면 배열보다는 더 유연하게 개체 그룹에 대해 작업할 수 있습니다. 배열과 달리 컬렉션에서는 응용 프로그램의 요구 변화에 따라 사용하는 개체의 그룹이 동적으로 증가하거나 줄어들 수 있습니다. 일부 컬렉션의 경우 키를 사용하여 개체를 빨리 검색할 수 있도록 컬렉션에 배치하는 개체에 키를 할당할 수 있습니다.

컬렉션은 클래스에 해당하므로 컬렉션에 요소를 추가하려면 먼저 새 컬렉션을 선언해야 합니다.

컬렉션이 한 데이터 형식의 요소만 포함하고 있으면 System.Collections.Generic 네임스페이스의 클래스 중 하나를 사용할 수 있습니다. 제네릭 컬렉션에서는 형식 안전성이 유지되므로 다른 데이터 형식을 컬렉션에 추가할 수 없습니다. 제네릭 컬렉션에서 요소를 검색할 때는 데이터 형식을 지정하거나 변환하지 않아도 됩니다.

참고

이 항목 예제의 경우 System.Collections.GenericSystem.Linq 네임스페이스를 위한 Imports 문(Visual Basic) 또는 using 지시문(C#)을 포함하십시오.

항목 내용

  • 간단한 컬렉션 사용

  • 컬렉션의 종류

    • System.Collections.Generic 클래스

    • System.Collections.Concurrent 클래스

    • System.Collections 클래스

    • Visual Basic 컬렉션 클래스

  • 키/값 쌍의 컬렉션 구현

  • LINQ를 사용하여 컬렉션에 액세스

  • 컬렉션 정렬

  • 사용자 지정 컬렉션 정의

  • 반복기

간단한 컬렉션 사용

이 섹션에 있는 예제는 강력한 형식의 목록으로 작업할 수 있는 일반적인 List 클래스 개체를 사용합니다.

다음 예제에서는 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 Each 문 대신 For…Next(Visual Basic) 또는 for(C#) 문을 사용할 수 있습니다. 인덱스 위치별로 컬렉션 요소에 액세스하여 수행합니다. 요소의 인덱스는 0에서 시작하며 요소에서 1을 차감한 숫자에서 끝납니다.

다음 예제는 For Each 대신 For…Next를 사용하여 컬렉션의 요소를 반복합니다.

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) 또는 for문(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 요소 형식에서는 고유한 클래스도 정의할 수 있습니다. 다음 예에서 List에서 사용되는 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 클래스

System.Collections.Generic 클래스

System.Collections.Generic 네임스페이스의 클래스 중 하나를 사용하여 제네릭 컬렉션을 만들 수 있습니다. 제네릭 컬렉션은 컬렉션 항목의 데이터 형식이 모두 같을 때 유용합니다. 제네릭 컬렉션을 사용하면 필요한 데이터 형식만 추가되도록 하여 강력한 형식 지정이 적용됩니다.

다음 표에는 System.Collections.Generic 네임스페이스의 자주 사용하는 일부 클래스가 나와 있습니다.

클래스

설명

Dictionary

키를 기반으로 구성된 키/값 쌍의 컬렉션을 나타냅니다.

List

인덱스로 액세스할 수 있는 개체 목록을 나타냅니다. 목록의 검색, 정렬 및 수정에 사용할 수 있는 메서드를 제공합니다.

Queue

FIFO(선입선출) 방식의 개체 컬렉션을 나타냅니다.

SortedList

연관된 IComparer 구현을 기반으로 키에 따라 정렬된 키/값 쌍의 컬렉션을 나타냅니다.

Stack

LIFO(후입선출) 방식의 개체 컬렉션을 나타냅니다.

자세한 내용은 일반적으로 사용되는 컬렉션 형식, Collection 클래스 선택System.Collections.Generic을 참조하십시오.

System.Collections.Concurrent 클래스

.NET Framework 4에서 System.Collections.Concurrent 네임스페이스의 컬렉션은 여러 스레드에서 컬렉션 항목에 액세스하기 위한 효율적이고 스레드로부터 안전한 작업을 제공합니다.

System.Collections.Concurrent 네임스페이스의 클래스는 여러 스레드에서 컬렉션에 동시에 액세스할 때마다 System.Collections.GenericSystem.Collections 네임스페이스의 해당 형식 대신 사용해야 합니다. 자세한 내용은 스레드로부터 안전한 컬렉션System.Collections.Concurrent을 참조하십시오.

System.Collections.Concurrent 네임스페이스에 포함된 일부 클래스는 BlockingCollection, ConcurrentDictionary, ConcurrentQueueConcurrentStack입니다.

System.Collections 클래스

System.Collections 네임스페이스의 클래스는 요소를 특정 형식의 개체로 저장하지 않고 Object 형식의 개체로 저장합니다.

가능하면 System.Collections 네임스페이스의 레거시 형식 대신 System.Collections.Generic 네임스페이스 또는 System.Collections.Concurrent 네임스페이스의 제네릭 컬렉션을 사용해야 합니다.

다음 표에는 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이 됩니다. 인덱스가 0에서 시작한다는 점에서 .NET Framework 컬렉션 클래스와 다릅니다.

가능하면 Visual Basic Collection 클래스 대신 System.Collections.Generic 네임스페이스 또는 System.Collections.Concurrent 네임스페이스의 제네릭 컬렉션을 사용해야 합니다.

자세한 내용은 Collection를 참조하십시오.

키/값 쌍의 컬렉션 구현

Dictionary 제네릭 컬렉션을 사용하면 각 요소의 키를 사용해서 컬렉션의 요소에 액세스할 수 있습니다. 값과 관련 키는 항상 사전에 함께 추가됩니다. 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
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}}
    };
}

다음 예제는 키로 항목을 빠르게 찾을 수 있도록 DictionaryContainsKey 메서드 및 Item 속성을 사용합니다. Item 속성을 사용하면 Visual Basic의 elements(symbol) 코드 또는 C#에서의 elements[symbol]을 사용함으로써 elements의 항목에 액세스할 수 있습니다.

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 시작를 참조하십시오.

다음 예제는 제네릭 List에 LINQ 쿼리를 실행합니다. LING 쿼리는 결과를 포함하는 다른 컬렉션을 반환합니다.

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에 저장된 Car 클래스 인스턴스를 정렬합니다. Car 클래스는 CompareTo 메서드를 구현해야 하는 IComparable 인터페이스를 구현합니다.

CompareTo 메서드에 호출할 때마다 정렬에 사용되는 비교가 한 번 수행됩니다. CompareTo 메서드에서 사용자가 작성한 코드는 현재 개체를 다른 개체와 비교할 때마다 값을 반환합니다. 현재 개체가 다른 개체보다 작으면 반환된 값이 0보다 작고 현재 개체가 다른 개체보다 크면 0과 같으며 둘 다 같으면 0입니다. 이렇게 하면 코드에 보다 큼, 보다 작음 및 같음 기준을 정의할 수 있습니다.

ListCars 메서드에서 cars.Sort() 문이 목록을 정렬합니다. List에 대해 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 또는 IEnumerable 인터페이스를 구현하여 컬렉션을 정의할 수 있습니다. 자세한 내용은 컬렉션 열거방법: foreach를 사용하여 컬렉션 클래스 액세스(C# 프로그래밍 가이드)를 참조하십시오.

사용자 지정 컬렉션을 정의할 수 있지만 이 항목의 앞부분의 Kinds of Collections에서 설명한 .NET Framework에 포함된 컬렉션을 사용하는 것이 일반적으로 더 좋습니다.

다음 예제에서는 AllColors이라는 사용자 지정 컬렉션 클래스를 정의합니다. 이 클래스는 GetEnumerator 메서드를 구현해야 하는 IEnumerable 인터페이스를 구현합니다.

GetEnumerator 메서드는 ColorEnumerator 클래스의 인스턴스를 반환합니다. ColorEnumerator는 Current 속성, MoveNext 메서드 및 Reset 메서드를 구현해야 하는 IEnumerator 인터페이스를 구현합니다.

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) 또는 yield return(C#) 문을 사용하여 각 컬렉션 요소를 한 번에 하나씩 반환합니다.

For Each…Next(Visual Basic) 또는 foreach(C#) 문을 사용하여 반복기를 호출합니다. For Each 루프의 각 반복이 반복기를 호출합니다. Yield 또는 yield return 문이 반복기에 도달하고, 식이 반환되고, 코드의 현재 위치가 유지됩니다. 다음에 반복기가 호출되면 이 위치에서 실행이 다시 시작됩니다.

자세한 내용은 반복기(C# 및 Visual Basic)을(를) 참조하십시오.

다음 예제에서는 반복기 메서드를 사용합니다. 반복기 메서드는 For...Next 루프(Visual Basic) 또는 for 루프(C#) 안에 있는 Yield또는yield return을 가지고 있습니다. 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

PLINQ(병렬 LINQ)

Collection 클래스 선택

컬렉션 내에서 비교 및 정렬

제네릭 컬렉션 사용 기준

기타 리소스

컬렉션을 사용하는 최상의 방법

프로그래밍 개념

컬렉션 및 데이터 구조

컬렉션 만들기 및 조작