简体   繁体   中英

Assign string array to two dimensional string array

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(';');

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 - ie, 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.

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[]>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM