Is there a built-in way to convert IEnumerator to IEnumerable?
The other answers here are ... strange. IEnumerable has just one method, GetEnumerator(). And an IEnumerable must implement IEnumerable, which also has just one method, GetEnumerator() (the difference being that one is generic on T and the other is not). So it should be clear how to turn an IEnumerator into an IEnumerable:
// using modern expression-body syntax
public class IEnumeratorToIEnumerable : IEnumerable
{
private readonly IEnumerator Enumerator;
public IEnumeratorToIEnumerable(IEnumerator enumerator) =>
Enumerator = enumerator;
public IEnumerator GetEnumerator() => Enumerator;
IEnumerator IEnumerable.GetEnumerator() => Enumerator;
}
foreach (var foo in new IEnumeratorToIEnumerable(fooEnumerator))
DoSomethingWith(foo);
// and you can also do:
var fooEnumerable = new IEnumeratorToIEnumerable(fooEnumerator);
foreach (var foo in fooEnumerable)
DoSomethingWith(foo);
// Some IEnumerators automatically repeat after MoveNext() returns false,
// in which case this is a no-op, but generally it's required.
fooEnumerator.Reset();
foreach (var foo in fooEnumerable)
DoSomethingElseWith(foo);
However, none of this should be needed because it's unusual to have an IEnumerator that doesn't come with an IEnumerable that returns an instance of it from its GetEnumerator method. If you're writing your own IEnumerator, you should certainly provide the IEnumerable. And really it's the other way around ... an IEnumerator is intended to be a private class that iterates over instances of a public class that implements IEnumerable.