Reputation: 13824
I have 2D array of string defined as
string[][] input_data;
I can count the number of rows by input_data.GetLength(0)
but if I use input_data.GetLength(1)
to get number of column, I always get
System.IndexOutOfRangeException was unhandled Message=Index was outside the bounds of the array. Source=mscorlib StackTrace: at System.Array.GetLength(Int32 dimension) ...
I also noticed that at debugging, when I hover my mouse on my array (after all the data has been inserted) it only shows the first value (number of row) like this: input_data| {string[18][]}
, if I continue expand the array then it shows all the 18 row data with the column data, like this:
How do I get the number of column? (in this case it is 139)
Upvotes: 0
Views: 4539
Reputation: 7
This is a jagged array. You can get the first dimensions size as 'input_data.GetLength(0)' and second dimension size as 'input_data.GetLength(1)'. Try it
Example:
string[,] input_data = new string[5,12];
var column1 = input_data.GetLength(0);
var column2 = input_data.GetLength(1);
Upvotes: 1
Reputation: 1076
GetLength(1) would work if you had a multidimensional array:
string[,] input_data = new string[27,139];
var columns = input_data.GetLength(1);
What you have now is a jagged array not a 2D array, so there is no guarantee that all items ('rows') have the same number of elements ('columns'). However in case you can't use multidimensional array for some reason and you are sure that the input will be that way you can use the length of the first element input_data[0].Length
Upvotes: 3
Reputation: 2447
I think you are confusing an array of arrays and a multi dimentional array, run this code :
string[][] array_of_arrays = new string[5][];
Console.WriteLine(array_of_arrays.Length);
array_of_arrays[0] = new string[5];
array_of_arrays[1] = new string[6];
Console.WriteLine(array_of_arrays[0].Length);
Console.WriteLine(array_of_arrays[1].Length);
string[,] multi_d_array = new string[4,2];
Console.WriteLine(multi_d_array.GetLength(0));
Console.WriteLine(multi_d_array.GetLength(1));
Upvotes: 2
Reputation: 131189
What you posted is a jagged array, not a multi-dimensional array. It's a 1-D array that contains other arrays. There is no second dimension so you can't use data.GetLength(1)
. Each row can have a different number of columns.
You can get the minimum or maximum number of columns for each row with data.Max(r=>r.Length)
or data.Min(r=>r.Length)
, eg:
var s=new string[][]{
new[] {"a","b"},
new[] {"a"}
};
Console.WriteLine("{0} {1}",s.Max(r=>r.Length),s.Min(r=>r.Length));
will print
2 1
To specify a multi-dimensional array, you need to use the [,]
syntax:
var s=new string[,]{
{"a","b"},
{"c","d"},
{"e","f"}
};
Console.WriteLine("{0} {1}",s.GetLength(0),s.GetLength(1));
This will return :
3 2
Upvotes: 9