方法 : 整数リストの反復子ブロックを作成する (C# プログラミング ガイド)

この例では、整数の配列を使用して SampleCollection リストを構築します。for ループは、コレクションを反復処理して各項目の値を生成します。次に、foreach ループを使用してコレクションの項目を表示します。

使用例

// 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 + " ");
        }
    }
}

出力

Values in the collection are:
5 4 7 9 3

参照

処理手順

方法 : ジェネリック リストの反復子ブロックを作成する (C# プログラミング ガイド)

関連項目

反復子の使用 (C# プログラミング ガイド)
yield (C# リファレンス)
Array

概念

C# プログラミング ガイド
反復子 (C# プログラミング ガイド)