Home > Software design >  Assign string array to two dimensional string array
Assign string array to two dimensional string array

Time:10-21

I'm a little bit confused. I try to assign a string array to a two dimensional string array. But get "Wrong number of indices" error. I understand the error, but should it not be possible to assign an array to the second dimension array field?

As sortedString has x number of fields with each an string array, should it not be possible to assign an string array to just a indexed field? (as the s.Split(';') already creates an array)

string[,] sortedString = new string[count,columns];
sortedString[counter] = s.Split(';');

CodePudding user response:

You're confusing a multidimensional array with a jagged array. sortedString is a 2-dimensional array of type string, so you must always provide the correct number of indices - in this case, 2. You can't say sortedString[x], you can only say sortedString[x, y].

You're probably thinking of a jagged array - i.e., a single-dimensional array, where each element is itself a (usually single-dimensional) array. Declare sortedString like this:

string[][] sortedString = new string[count][];

This will allow each "inner" array to be of a different length (depending on how many ; there are in each s), which might not be what you want.

CodePudding user response:

C# has two kinds of 2D arrays. If you need access to one dimension at a time as it's own array, you must use the "jagged" variety, like this:

string[][] sortedString = new string[count][];
for(int i = 0; i<sortedString.Length;i  )
    sortedString[i] = new string[columns];

Or, even better:

var sortedString = new List<string[]>;
  • Related