Monty’s Gush

IEnumerator.Next(count)

Posted on: March 31, 2009

I still find it remarkable how syntax alone can alter the way I conceptualise a problem.

Here’s a useful helper for pulling the next n elements out of an enumerator. Think of it as a generalisation of MoveNext. I’ve found it handy for implementing certain IEnumerable extensions.

public static class EnumeratorExtensions
{
    /// <summary>
    /// Returns a specified number of contiguous elements
    /// from the enumerator.
    /// </summary>
    public static IEnumerable<T> Next<T>(
        this IEnumerator<T> source,
        int count)
    {
        int counter = 0;

        while (counter < count)
        {
            if (source.MoveNext())
                yield return source.Current;
            else
                break;

            counter++;
        }
    }
}

1 Response to "IEnumerator.Next(count)"

[…] Contact IEnumerator.Next(count) […]

Leave a comment