Reversing through the object in a List is an operation that isn’t so uncommon, and there is a simple way of doing this using a for loop with a decrement on an index value. But it isn’t a particularly elegant way of acheiving this and the re-use of the for loop isn’t the most efficient in terms of code re-use. Thankfully with the use of the IEnumerable interface we can create a simple, clean and elegant solution to the problem.
By deriving from the IEnumerable interface we can create a new GetEnumerator method and do the meat of the work here. Below is a class that implements this interface to create a reversable enumerator dependant on a simple local property. The property is from a simple enumeration that is defined as Forwards or Reverse.
public sealed class Counts : List<long>, IEnumerable<long>
{
/// <summary>
/// The direction to iterate through our collection
/// </summary>
private IteratorDirection iteratorDirection = IteratorDirection.Forwards;
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref=”T:System.Collections.Generic.IEnumerator`1″></see>
/// that can be used to iterate through the collection.
/// </returns>
public new IEnumerator<long> GetEnumerator()
{
if(iteratorDirection == IteratorDirection.Forwards)
{
for (int i = 0; i < Count; i++)
{
yield return this[i];
}
}
else
{
for (int i = Count – 1; i >= 0; i–)
{
yield return this[i];
}
}
}
/// <summary>
/// Sets the iterator direction.
/// </summary>
/// <value>The iterator direction.</value>
public IteratorDirection IteratorDirection
{
set { iteratorDirection = value; }
}
}
To use the class is simple… First set the direction that you want to iterate through the collection, then iterate through the collection using the ubiquitous foreach loop
OurCounts.IteratorDirection = IteratorDirection.Forwards;
foreach (long count in OurCounts)
{
}
OurCounts.IteratorDirection = IteratorDirection.Reverse;
foreach (long count in OurCounts)
{
}