If I am walking through an IEnumerable<T>, is there any way to get a new IEnumerable<T> representing the remaining items after the current one.
For example, I would like to write an extension method IEnumerator<T>.Remaining():
IEnumerable<int> sequence = ...
IEnumerator<int> enumerator = sequence.GetEnumerator();
if (enumerator.MoveNext() && enumerator.MoveNext()) {
IEnumerable<int> rest = enumerator.Remaining();
// 'rest' would contain elements in 'sequence' start at the 3rd element
}
I’m thinking of the collection of a sort of singly-linked list, so there should be a way to represent any remaining elements, right? I don’t see any way to do this exposed on either IEnumerable<T> or IEnumerator<T>, so maybe it’s incompatible with the notion of a potentially unbounded, nondeterministic sequence of elements.
If you must use
IEnumerator<T>and notIEnumerable<T>(where all the good extension methods are) here’s two simple methods.This one can only be enumerated a single time (and is bound to the original enumerable, which means you can end up with exceptions if another thread changes the source list):
And this one builds a list and can be enumerated repeatedly (and is disconnected from the original enumerator so you don’t have to worry about your source IEnumerable changing):