Ronaldinho Learn Coding Ronaldinho Learn Coding - 9 months ago 59
C# Question

how to get length of string [] []

I have 2D array of string defined as

string[][] input_data;

I can count the number of rows by

but if I use
to get number of column, I always get

System.IndexOutOfRangeException was unhandled
Message=Index was outside the bounds of the array.
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:

enter image description here

How do I get the number of column? (in this case it is 139)

Answer Source

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[,]{

Console.WriteLine("{0} {1}",s.GetLength(0),s.GetLength(1));

This will return :

3 2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download