Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert multidimensional array to list of single array

Tags:

c#

I have a multi dimensional array which i need to convert to a list of arrays. Not one single array, but for each iteration of the first dimension i need a separate array containing the values in the second dimension.

How do I convert this:

int[,] dummyArray = new int[,] { {1,2,3}, {4,5,6}};

into a list<int[]> holding two arrays with values {1,2,3} and {4,5,6}?

like image 536
martijn Avatar asked Oct 24 '25 14:10

martijn


2 Answers

You can convert 2d array into jagged array and then convert it to List.

int[,] arr = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };

int[][] jagged = new int[arr.GetLength(0)][];

for (int i = 0; i < arr.GetLength(0); i++)
{
    jagged[i] = new int[arr.GetLength(1)];
    for (int j = 0; j < arr.GetLength(1); j++)
    {
        jagged[i][j] = arr[i, j];
    }
}

List<int[]> list = jagged.ToList();
like image 127
M.kazem Akhgary Avatar answered Oct 27 '25 05:10

M.kazem Akhgary


You can use Linq:

int[,] dummyArray = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
int count = 0;
List<int[]> list = dummyArray.Cast<int>()
                    .GroupBy(x => count++ / dummyArray.GetLength(1))
                    .Select(g => g.ToArray())
                    .ToList();
like image 45
Eser Avatar answered Oct 27 '25 05:10

Eser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!