Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular lists in C#

Tags:

c#

I am not very experienced with C#. I am trying to build circular lists and I have done it like this:

public List<string> items = new List<string> {"one", "two", "three"};
private int index = 0;

void nextItem() {
    if (index < items.Count - 1)
        index += 1;
    else
        index = 0;

    setItem();
}

void previousItem() {
    if (index > 0)
        index -= 1;
    else
        index = items.Count - 1;

    setItem();
}

void Update() {
         if (Input.GetKeyDown(KeyCode.RightArrow)) nextItem();
    else if (Input.GetKeyDown(KeyCode.LeftArrow))  previousItem();
}

But now I am wondering: Am I reinventing the wheel? Does C# already come with a proper data structure for this?

EDIT: In case some context is needed. I have a game menu, where I display a collection of items, and I want that when I press "next" and Im at the last one, to show the first item again.

like image 590
Enrique Moreno Tent Avatar asked Nov 18 '15 13:11

Enrique Moreno Tent


1 Answers

With utilization of the % (remainder) operator your code gets quite simple:

void nextItem() {
    index++; // increment index
    index %= items.Count; // clip index (turns to 0 if index == items.Count)
    // as a one-liner:
    /* index = (index + 1) % items.Count; */

    setItem();
}

void previousItem() {
    index--; // decrement index
    if(index < 0) {
        index = items.Count - 1; // clip index (sadly, % cannot be used here, because it is NOT a modulus operator)
    }
    // or above code as a one-liner:
    /* index = (items.Count+index-1)%items.Count; */ // (credits to Matthew Watson)

    setItem();
}
like image 73
Binkan Salaryman Avatar answered Sep 18 '22 00:09

Binkan Salaryman