tags:

views:

204

answers:

5

I have a collection of objects in a generic list.

I am wondering what is the the best way to navigate this collection. I want to do operations such as "MoveNext", "MovePrevious" etc.

Basically my collection is a number of steps in a flow and I want to be able to move along the steps.

Is there a c# equivalent of MoveNext and MovePrevious in Sql

+5  A: 

You can use the LinkedList<T> class.
Each element has a reference to the previous and the next one.
Check the link to the documentation for examples.

Paolo Tedesco
That might work fine
Solyad
The LinkedList<T> object worked. Took me a while to get a system worked out to find the node position based on a search parameter and activate controls accordingly (I'm building a primitive workflow manager on a dynamic form system and I want to be able to "ask" it where is it in the flow so that i can activate some controls, change the form setup and bring the user back to the same point in the chain later). I think this will work.
Solyad
A: 

I am not aware of built in functionality to do this, but you can do this very simply by having a variable holding the index. When you want MoveNext then i++ and when you want MovePrevious use i-- (That is assuming you use i as the variable).

EDIT: I was wrong. Here is a snippet from MSDN that does just what you ask. I haven't looked deeply into it, but it was in the article about StringCollections

public static void PrintValues2( StringCollection myCol )  {
      StringEnumerator myEnumerator = myCol.GetEnumerator();
      while ( myEnumerator.MoveNext() )
         Console.WriteLine( "   {0}", myEnumerator.Current );
      Console.WriteLine();
   }
Adkins
+3  A: 

Just add a Current property to your list.

not tested. just looks right.

and there is a guard you should implement to your liking, e.g. the starting index. should you start at -1 and require a movenext? up to you

   public class BackAndForthList<T> : List<T>
    {
        private int _current = 0;

        public T Current
        {
            get { return this[_current]; }
        }

        public void MoveNext()
        {
            _current++;
            if (_current >= Count)

            {
                _current = 0;
            }
        }

        public void MovePrevious()
        {
            _current--;

            if (_current < 0)
            {
                _current = Count - 1;
            }
        }
    }
Sky Sanders
That might work nicely too. Why can't I mark two answers in stackoverflow ;) Oh well, thanks, have a vote at least!
Solyad
+1  A: 

For moving forward you could use an Enumerator:

list.GetEnumerator().MoveNext()

http://shiman.wordpress.com/2008/07/25/enumerators-in-c-net/

martin
A: 

Use a BindingList or BindingSource or derive your own from either.

leppie