Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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]);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top