Circular Lists in C #

I am not very good at C #. I am trying to create circular lists and I did 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 wonder: am I inventing the wheel? Does C # already have a suitable data structure for this?

EDIT: If necessary, some context. I have a game menu in which I display a collection of items, and I want when I click "next" and Im on the last to display the first item again.

+4
source share
1 answer

Using the operator %(remainder) your code becomes 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();
}
+6
source

Source: https://habr.com/ru/post/1616383/


All Articles