April 13, 2007

Simple C# IEnumerable Samples

This example shows how the iterator can be exposed to allow an object to be iteratied in different ways, In this case a matrix type object can be iterated row by row or column by column. The advantage of the iterator is that it only gets a value when asked.

// Iterate column by column starting with Pin 1,1
public IEnumerable<Thing> ColumnByColum()
{
    Thing rcl = new Thing();
    for (int col = 0; col < Cols; col++)
    {
        for (int row = 0; row < Rows; row++)
        {
            rcl.Row = row + 1;
            rcl.Column = col + 1;
            yield return rcl;
        }
    }
}

// Iterate row by row starting with Pin 1,1
public IEnumerable<Thing> RowByRow()
{
    Thing rcl = new Thing();
    for (int row = 0; row < Rows; row++)
    {
        for (int col = 0; col < Cols; col++)
        {
            rcl.Row = row + 1;
            rcl.Column = col + 1;
            yield return rcl;
        }
    }
}


foreach (Thing thing in matrixThingey.ColumnByColum)
{
}
There are 2 yield statements:
  • "yield return XXX" returns an item.
  • "yield break" ends the iterator without returning any item. You can think of yield break as return statement which does not return a value.

No comments: