简体   繁体   中英

C# Initializing a Multi-dimensional array with multiple 1D arrays

I'm trying to initialize a two-dimensional array using two existing 1D arrays. Obviously, if we know the values of these arrays, we can initialize it like such:

float[,] my2DArray = new float{{1,2}, {3,4}};

However, if I try to initialize the array with variables like this:

float[] a = {1,2};
float[] b = {3,4};
float[,] my2DArray = new float{a,b};

then I get an error "A nested array initializer is expected." I'm guessing maybe this has something to do with the compiler not knowing the dimensions of the array since it won't be allocated until runtime.

So, is there any way I can work around this to do this sort of array assignment? I am targeting .NET 4.0.

You'll need to initialize the array yourself. You can get a performance improvement and shorter code than looping by using Buffer.BlockCopy , but can't do an inline initialization directly:

float[] a = {1,2};
float[] b = {3,4};
float[,] my2DArray = new float[a.Length, 2];

int len = a.Length * sizeof(float);
Buffer.BlockCopy(a, 0, my2DArray, 0, len);
Buffer.BlockCopy(b, 0, my2DArray, len, len);

Note that you'll have to guarantee that the source arrays are the same length for this to work.

float[] a = { 1, 2 };
float[] b = { 3, 4 };

float[,] my2DArray = new float[a.Length, b.Length];

for (int i = 0; i < a.Length; i++)
    for (int j = 0; j < b.Length; j++) 
         my2DArray[i, j] = new float[][] { a, b }[i][j];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM