I have a problem extracting the columns length in jagged array like this:

How can I get the length of the 2nd (with index 1 and length 8) or the 5th (index 4 and length 4) column for example? Same with the rows. I need length of a specified row.
The method getColumnLength just goes through each row and checks if the row is long enough for the column to be in it. If it is then add it to the count of rows that have that column.
public class Program {
public static void Main(string[] args) {
int[][] jaggedArray = {
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};
Console.WriteLine(getColumnLength(jaggedArray, 4));
Console.WriteLine("Press any key to continue. . .");
Console.ReadKey();
}
private static int getColumnLength(int[][] jaggedArray, int columnIndex) {
int count = 0;
foreach (int[] row in jaggedArray) {
if (columnIndex < row.Length) count++;
}
return count;
}
}
You should be able to get the row length fairly easily as that is simply going to be the length of an individual array in your array of arrays. For example: arrays[3].length would be 8.
Columns is different because we need information about every array. We can iterate through, counting the number of arrays whose lengths are greater than the column number you're looking for.
public static int getColumnLength(int[][] arrays, int columnNumber) {
int count = 0;
for(int i = 0; i < arrays.length; i++) {
if (arrays[1].length > columnNumber) {
count++;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With