Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeatedly Iterating Through a List

I have a list like such:

List<Thing> foo = new List<Thing>();
foo.PopulateWithFourThings();

And I want to iterate through it over and over, such as 0123012301230123...

Foreach is not what I am looking for, because I do not want everything all at once. I have been messing with Queues, and am wondering if Queues are appropriate here? Or if there is something better than Queues for this.

I am looking for the best code practice in this situation (repeatedly iterate through a list).

So is there a better option than:

    if (nextElementIsNeeded)
    {
        Thing thing = foo[0];
        foo.RemoveAt(0);
        foo.Add(thing);
        return thing;
    }

Or the following code using a Queue:

    Queue<Thing> foo = new Queue<Thing>();
    foo.PopulateWithForThings();
    //////////////////////////////////////
    if (nextElementIsNeeded)
    {
        Thing thing = foo.Dequeue();
        foo.Enqueue(thing);
        return thing;
    }
like image 498
Evorlor Avatar asked Feb 11 '23 22:02

Evorlor


1 Answers

Instead of constantly adding and removing the same Items to/from a collection (no matter which type), simply use a circular index to access the list you have.

int currentElementIndex = 0;
//..

if (nextElementIsNeeded)
{ 
  currentElementIndex = (currentElementIndex + 1) % foo.Count;
  thing = foo[currentElementIndex]; 
} 
like image 159
TaW Avatar answered Feb 15 '23 10:02

TaW