C# – Select next child in array using c#

arraysc++

I have an array,

 string [] myString = new string["2","1","3","2","1","2"];

And I want when I select one child I will get the next child value, That is to say, when I select the first one"2" , I will get the value of the second"1"…When I select the second one "1",I will get the value of the third one"3"…and so on…
I try to use index method, here is my code:

foreach (var index in myString){
int myindex = myString.indexOf(index);
}

Well, it is not the correct method…Any one know, how to do that? Thanks

Best Solution

So I'm assuming that you want a function that will take the string[] and an int and return the next element (or the first element - if the int value indicates the last element). Something like this will do the trick ... (note I've just thrown the code in here without attempting to compile or testing so may need a tweak or two).

public string GetNextElement(string[] strArray, int index)
{
    if ((index > strArray.Length -1) || (index < 0))
       throw new Exception("Invalid index");

    else if (index == strArray.Length -1)
       index = 0;

    else
       index++;

    return strArray[index];
}

for a list you would have something like (assuming you always have a list of string objects - use ToString() otherwise)

    public string GetNextElement(IList<string> list, int index)
    {
        if ((index > list.Count - 1) || (index < 0))
            throw new Exception("Invalid index");

        else if (index == list.Count - 1)
            index = 0;

        else
            index++;

        return list[index];
    }