0
public static void matrix(List<List<int>> matrix)
{
    //matrix.Count is for amount of Row here
}

Example

Here the jagged array is

{{ 1,  2,  3},
 { 4,  5,  6},
 { 7,  8,  9},
 {10, 11, 12}}

Then matrix.Count gives 4.

Here I want column count.

If this is array instead of List then I can use matrix.GetLength(0) and matrix.GetLength(1) to find Row count and Column count?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Aaqil Ahmed
  • 3
  • 1
  • 4
  • Try Using ToList() – jdweng Aug 21 '21 at 07:20
  • It is not a [2D](https://docs.microsoft.com/dotnet/csharp/programming-guide/arrays/multidimensional-arrays) list but rather a [jagged array](https://docs.microsoft.com/dotnet/csharp/programming-guide/arrays/jagged-arrays) as it is [managed underlying](https://referencesource.microsoft.com/). Also this is not a (standard) [matrix](https://en.wikipedia.org/wiki/Matrix_(mathematics)) (as I know), whatever here the example looks like a 3x4 matrix. (special case). Thus talking about a column count or number or index is irrelevant, I think. It is more a level (nodes count) like in trees/graphs. –  Aug 21 '21 at 08:42
  • Related: [What are the differences between a multidimensional array and an array of arrays in C#?](https://stackoverflow.com/questions/597720/) • [Why we have both jagged array and multidimensional array?](https://stackoverflow.com/questions/4648914/) –  Aug 21 '21 at 08:47
  • 1
    Does this answer your question? [Get Length Of Columns in Jagged Array](https://stackoverflow.com/questions/41049205/get-length-of-columns-in-jagged-array) –  Aug 21 '21 at 08:48
  • What do you expect from the example provided for `GetColumnCount (matrix)`? What about the sample from answers of @.MrMoeinM and @.DmitryBychenko? –  Aug 21 '21 at 08:51

2 Answers2

1

In general case, since you have jagged structure you can define different ColCount:

 {
  { 1, 2, 3  },  // Average Columns - 3
  { 4, 5, 6, 7}, // Max Columns - 4
  { 8, 9},       // Min Columns - 2
 }

Assuming that null list has 0 columns you can put:

 using System.Linq;

 ...

 int minColCount = matrix.Min(list => list?.Count ?? 0); 
 int maxColCount = matrix.Max(list => list?.Count ?? 0);
 int avgColCount = (int)Math.Round(matrix.Average(list => list?.Count ?? 0));

If you can guarantee that matrix is rectangular and doesn't contain null, you can put

 int colCount = matrix.Count > 0 ? matrix[0].Count : 0; 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

You are using a list of list of int. In this situation, there is no guaranty that you have a matrix with fix column size.

For example { {1}, {4,5,6}, {7,8}, {10,11,12,13} } is a possible combination.

But, if you are sure inside lists have the same size you can get the first list's size.

int column = matrix?.FirstOrDefault()?.Count ?? -1;

Don't forget to add using System.Linq; at top of your code.

MrMoeinM
  • 2,080
  • 1
  • 11
  • 16