Reputation: 137108
I have the following code:
int index = currentIndex;
do
{
if (index == list.Count - 1)
{
// At the end, cycle round to the start
index = -1;
}
index++;
}
while (list[index] satisfies some condition);
// Do something with list[index]
currentIndex = index;
which clearly works and isn't really that inefficient.
However, this code gets called quite a few times and I was wondering if it could be made more efficient or cleaner in some way.
Upvotes: 0
Views: 267
Reputation: 141565
In case nonempty list you can use remainder operator:
index = index % list.Count
as for efficiency it is needed to be benchmarked.
UPD
as Šimon Kocúrek said in the comments you can merge increment and reminder into one operation:
index = (index + 1) % list.Count
Upvotes: 2