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;
}
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With