Boubacar Traoré
Boubacar Traoré

Reputation: 359

Extracting a column from a specific multi-dimensional array in C#

I'm having trouble while attempting to extract a row from my array. This is my code :

using System;

namespace C_sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!. This is the one !");

            dynamic[] res = new Object[3];

            res[0] = new int[2,2]{{3,2},{16,9}};
            res[1] = new int[2,2]{{4,7},{6,29}};
            res[2] = new int[2,2]{{30,29},{5,49}};

            //dynamic resultat = res[0][0];

        }
    }
}

As you can see, at the end of my program, the contents of my local variable res looks like this :

[0] [dynamic]:{int[2, 2]}
[0, 0] [int]:3
[0, 1] [int]:2
[1, 0] [int]:16
[1, 1] [int]:9
[1] [dynamic]:{int[2, 2]}
[0, 0] [int]:4
[0, 1] [int]:7
[1, 0] [int]:6
[1, 1] [int]:29
[2] [dynamic]:{int[2, 2]}
[0, 0] [int]:30
[0, 1] [int]:29
[1, 0] [int]:5
[1, 1] [int]:49

Now, I want to put only the first row of res[0] in my variable resultat in order to get a 1D array. So, at the end of the process, resultat should be equal to :

[0] [int]:3
[1] [int]:2

I've already tried res[0][0,] and res[0][0:]. None of them worked. Any help ?

Upvotes: 0

Views: 657

Answers (1)

Bagdan Imr
Bagdan Imr

Reputation: 1286

You can flatten 2d array using .Cast<int>() and then take first row using .Take(2):

const int arraySize = 2;
var resultat = (res[0] as int[,]).Cast<int>().Take(arraySize).ToArray();

In general case for an arbitrary row index you can use .Skip(arraySize * rowIndex)

If it is too slow for you, you may try Buffer.BlockCopy:

const int rowSize = 2;
const int intSize = 4;

int[] resultat = new int[rowSize];
Buffer.BlockCopy(res[0], 0, resultat, 0, intSize * rowSize);

In general case it would be

const int intSize = 4; // Size of integer type in bytes

int[,] matrix = res[0];

int rowSize = matrix.GetLength(1); // Get size of second 2d-array dimension

int rowIndex = 0; // Index of a row you want to extract

int[] resultat = new int[rowSize];
Buffer.BlockCopy(res[0], // Copy source
            rowSize * intSize * rowIndex, // Source offset in bytes
            resultat, // Copy destination
            0,  // Destination offset
            intSize * rowSize); // The number of bytes to copy 

Buffer.BlockCopy documentation

Upvotes: 1

Related Questions