Posted by: Pete Montgomery 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 | IEnumerable.GroupsOf(n) « Monty’s Gush
April 1, 2009 at 10:58 am
[...] Contact IEnumerator.Next(count) [...]