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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: