'C#. Given an Enumerator, iterate till end to produce an enumerable
In C#, I would like to write an extension method that would take an Enumerator<T> and give back an IEnumerable<T>. This could prove useful, for example, if I had to enumerate to some point in a list and then want a list with current element (if enumeration has started) plus the remaining elements.
Here's a simple implementation I started out with
public static IEnumerable<T> Enumerate<T>(this IEnumerator<T> enumerator)
{
do
{
yield return enumerator.Current;
}
while (enumerator.MoveNext());
}
Problem I am having is that if enumeration hasn't already started then this would add a default value of T to the sequence (as its first element). Is there any way to work around this/ without having to pass in additional arguments.
Solution 1:[1]
You need the .MoveNext() call before the yield statement.
public static IEnumerable<T> Enumerate<T>(this IEnumerator<T> enumerator)
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
};
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JAlex |
