I work with C# I have the need to convert a list to a multidimensional array
What they send me on the list is the following
int[,] matriz = new int[,] { { 1, 2, 2 }, { 3, 4, 3 }, { 5, 6, 1 } };
But they are sending it as follows
List<List<int>> arr
I need to convert that list to a multidimensional array so that it looks like this
int[,] matriz = new int[,] { { 1, 2, 2 }, { 3, 4, 3 }, { 5, 6, 1 } };
How to convert that list to Array?
What happens is that I solved an exercise in the way that it is a multidimensional array but when it comes to implementing the code I am surprised that it is a list
int sumaDiagonalI = 0;
int sumaDiaganalD = 0;
int[,] matriz = new int[,] { { 1, 2, 2 }, { 3, 4, 3 }, { 5, 6, 1 } };
int cantFilas = matriz.GetLength(0);
int cantColumnas = matriz.GetLength(1);
if (cantFilas != cantColumnas)
{
Console.WriteLine("No es una matriz cuadrada");
return;
}
var indiceMáximo = Math.Min(cantFilas, cantColumnas);
for (var i = 0; i < indiceMáximo; i++)
{
sumaDiagonalI += matriz[i, i];
}
int j = 0;
for (int i = 0; i < cantFilas; i++)
{
j = ((cantFilas - 1) - i);
sumaDiaganalD += matriz[i, j];
}
In this algorithm I add the left and right diagonals
You have the list:
Where each element of the list is itself a list of integers.
Therefore, the columns will be the number of elements that the sublists of the main list have, as you say that all those sublists have the same length, so you can use any sublist of the main list to obtain the number of columns. Therefore we take the first position of the main list (the first sublist).
We use the ElementAt(int) method to which an integer is passed as a parameter, which indicates the index that the element occupies in the list. In this case we obtain the first element of the list (index 0) and since this first element is a list too, we apply the Count() method to it and thus obtain the number of columns.
To get the rows we do the following:
In this way we obtain the number of elements that the main list stores, that is, the number of rows.
Then comes the construction of the matrix:
And now the filling of the matrix would come:
We do two nested fors, one to loop through the main list and the other to loop through each sublist of the main list. We get each subList from the main list and with this subList we fill the matrix