2

I am programming in C# and I currently have the 2D array below:

int[,] results = {                                  
{ 4, 7, 9, 3, 8, 6, 4},                                  
{ 4, 8, 6, 4, 8, 5, 6},                                  
{ 7, 3, 9, 2, 2, 1, 8}    
};

I'd like to create a loop or function which outputs 3 separate arrays, copying the values from each row.

e.g. output:

row1 = {4, 7, 9, 3, 8, 6, 4}    
row2 = {4, 8, 6, 4, 8, 5, 6}

etc

I have been able to copy the values of each row into a separate string which is then written in the console with this line of code:

for (int a = 1; a < (rows+1); a++)                
{                    
    for (int b = 1; b < (columns+1); b++)                    
    {                        
        scores = scores + " " + results[(a-1), (b-1)];                    
    }                    
    scores = "";                
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • Possible duplicate of [How to copy a row of values from a 2D array into a 1D array?](http://stackoverflow.com/questions/797354/how-to-copy-a-row-of-values-from-a-2d-array-into-a-1d-array) –  Apr 08 '16 at 06:49

3 Answers3

3

you need a convertion from a 2D array into a jagged array

int[,] array = {  { 4, 7, 9, 3, 8, 6, 4},
                    { 4, 8, 6, 4, 8, 5, 6},
                    { 7, 3, 9, 2, 2, 1, 8}
                };            

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

int[] row1 = jagged[0];
int[] row2 = jagged[1];
int[] row3 = jagged[2];

difference between multidimensional array and jagged array:

//multidimensional array
int[,] multi = { { 7, 2, 6, 1 }, { 3, 5, 4, 8 } };
//array of arrays (jagged array) 
int[][] jagged = new int[][] { new int[] { 7, 2, 6, 1 }, new int[] { 3, 5, 4, 8 } };
fubo
  • 44,811
  • 17
  • 103
  • 137
1

LINQ variant:

var m0 = new int[,] { { 1, 2 }, { 3, 4 } };
var rows = Enumerable.Range(0, m0.GetLength(0)).Select(i => Enumerable.Range(0, m0.GetLength(1)).Select(j => m0[i, j]));
foreach (var r in rows) Console.WriteLine(string.Join(" ", r));
Console.ReadLine();

a 'smarter' variant (flattern an array and take by N values):

var rows = m0.Cast<int>().Select((v, i) => new { i = i / m0.GetLength(1), v }).GroupBy(e => e.i).Select(g => g.Select(e => e.v));
Mike Tsayper
  • 1,686
  • 1
  • 17
  • 25
0

Just a piece of cake using JsonSoft as

var json = JsonConvert.SerializeObject(results);
int[][] arr = JsonConvert.DeserializeObject<int[][]>(json);

int[] arr1 = arr[0];
int[] arr2 = arr[1];
int[] arr3 = arr[2];
M.S.
  • 4,283
  • 1
  • 19
  • 42