tags:

views:

189

answers:

3

In my c# app, I've got a list that I navigate with an Enumerator. It works great for moving forward through the list, but the Enumerator class doesn't have a MoveBack method.

Is there different class that has a MoveBack method, or do I need to write my own?

A: 

Any enumerators using the IEnumerator interface by definition must start before the first element and iterate forwards through the collection. In short: they don't support backwards traversal.

If you want backwards traversal you'll need to write your own enumeration functions that allow you start anywhere you want.

Ron Warholic
A: 

You could reverse the list and interate over that. Or, with some classes, you could do a for loop from end to beginning and use ElementAt().

tvanfosson
A: 

Sometimes I had to deal with such a situation with certain C++ STL containers that only provide a forward iterator. If you know in advance how many elements backwards you need to go, you might do something like this:

IEnumerator<int> e1 = yourListOfInt.GetEnumerator();
IEnumerator<int> e2 = e1;
for (int i = 0; i < 3; ++i) e2.MoveNext();

Now e1 is three elements ahead of e2. That was the only solution I had in C++ some years ago.

But if you're using a list, I assume you may access it by index?

Hosam Aly