How to find the column count of list of lists in C#?

1.2k Views Asked by At
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?

2

There are 2 best solutions below

0
MrMoeinM On

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.

0
Dmitry Bychenko On

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;