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

更新 : 2007 年 11 月

この例では、整数の配列を使用して SampleCollection リストを構築します。for ループは、コレクションを反復処理して yield ステートメントで各項目の値を返します。次に、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 + " ");
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    Values in the collection are:
    5 4 7 9 3        
*/

参照

処理手順

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

概念

C# プログラミング ガイド

参照

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

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

Array

yield (C# リファレンス)