Partager via


How to: Create an Iterator Block for a List of Integers (C# Programming Guide) 

In this example, an array of integers is used to build the list SampleCollection. A for loop iterates through the collection and yields the value of each item. Then a foreach loop is used to display the items of the collection.

Example

// Declare the collection:
public class SampleCollection
{
    public int[] items;

    public SampleCollection()
    {
        items = new int[5] { 5, 4, 7, 9, 3 };
    }

    public System.Collections.IEnumerable BuildCollection()
    {
        for (int i = 0; i < items.Length; i++)
        {
            yield return items[i];
        }
    }
}

class MainClass
{
    static void Main()
    {
        SampleCollection col = new SampleCollection();

        // Display the collection items:
        System.Console.WriteLine("Values in the collection are:");
        foreach (int i in col.BuildCollection())
        {
            System.Console.Write(i + " ");
        }
    }
}

Output

Values in the collection are:
5 4 7 9 3

See Also

Tasks

How to: Create an Iterator Block for a Generic List (C# Programming Guide)

Reference

Using Iterators (C# Programming Guide)
yield (C# Reference)
Array

Concepts

C# Programming Guide
Iterators (C# Programming Guide)