Is there a built-in way to convert IEnumerator to IEnumerable?
The easiest way of converting I can think of is via the yield statement
public static IEnumerable ToIEnumerable(this IEnumerator enumerator) {
while ( enumerator.MoveNext() ) {
yield return enumerator.Current;
}
}
compared to the list version this has the advantage of not enumerating the entire list before returning an IEnumerable. using the yield statement you'd only iterate over the items you need, whereas using the list version, you'd first iterate over all items in the list and then all the items you need.
for a little more fun you could change it to
public static IEnumerable Select(this IEnumerator e,
Func selector) {
while ( e.MoveNext() ) {
yield return selector(e.Current);
}
}
you'd then be able to use linq on your enumerator like:
IEnumerator enumerator;
var someList = from item in enumerator
select new classThatTakesTInConstructor(item);