문제

I'm iterating through a string list (storedProcedures) and splitting each list item into an array. I would like to then access the array elements using specific indices. I am getting an out of range exception as soon as I try to access the second element of the array.

string[] myArray = new string[4];
foreach (string procedure in storedProcedures)
{
    myArray = procedure.Split(',');

    foreach (string index in myArray)
    {
        Console.WriteLine(index);
    }

    for (int i = 0; i < myArray.Length; i++)
    {
        Console.WriteLine(myArray[i]);
    }

    Console.WriteLine(myArray[0]);
    Console.WriteLine(myArray[1]);  <---- out of range exception here
    Console.WriteLine(myArray[2]);
    Console.WriteLine(myArray[3]);
}

Accessing the array and printing its contents using the 'foreach' and 'for' loops work fine, so I'm not sure why accessing the array by specifying the indices directly doesn't work?

도움이 되었습니까?

해결책

This is useless:

string[] myArray = new string[4];

because this throws your array away:

myArray = procedure.Split(',');

Your problem is that one of storedProcedures does not have a comma in it.

다른 팁

What does Console.WriteLine(myArray.Length) show? You start the array out with a size of 4, but procedure.Split(',') gave you a new array, which possible only has one element in it.

Probably your split array is shorter than expected. You should always check for length before retrieving values out of arrays. Maybe some commas are missing, maybe your strings are not properly formatted... debug it better, like so:

foreach (String procedure in storedProcedures)
{
    Console.WriteLine("Current Procedure: \"" + procedure + "\"");

    String[] split = procedure.Split(',');

    Console.WriteLine("Split Length: " + split.Length.ToString());

    for (int i = 0; i < myArray.Length; i++)
        Console.WriteLine(i.ToString() + ") " + split[i]);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top