Inverted enumerator

  • Thread starter Thread starter Fernando Rodríguez
  • Start date Start date
F

Fernando Rodríguez

HI,

Is there an IEnumerator that enumerates a Collection from the back to the
begining?

Thanks
 
Fernando,

There is nothing like this in the framework out of the box.
Implementing something would be easy though, but could have adverse effects.
Basically, you would have to enumerate through the complete collection,
storing all of the elements. You would then return them in the reverse
order. This would cause a hit performance-wise in the initial fetch. If
your collections are small though, this shouldn't be an issue.

If your collections are big, then you might want to adjust your logic to
work with in the reverse order.

Hope this helps.
 
The answer is no to both of your enumerator questions, mainly because
enumerators are designed as the simplest way to step through containers, so
that they can be used on *any* container.

For some types of container (such as singly-linked lists) there's just
no way of going from the end to the beginning.

BUT....

Just because such an object doesn't exist among those in the framework,
doesn't mean your can't write one for your collection class, assuming that
it can handle the concept:

// Warning -- Untested code ahead

class ReverseArrayEnumerator : IEnumerator
{
private System.Array _array;
private int index _index;

ReverseArrayEnumerator(System.Array a)
{
_array = a;
_index = a.Length;
}

// IEnumerator members
bool MoveNext()
{
_index --;
return _index >= 0;
}

void Reset()
{
_index = array.Length;
}

object Current
{
get
{
return _array[_index];
}
}

// Special member, just for you
int Index
{
// Returns position from start. If you want index from end, that
would be "_array.Length - index;"
get
{
return _index;
}
}
}
--
Truth,
James Curran
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
(note new day job!)
 
Back
Top