Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array concatenation in C#

  1. How do I smartly initialize an Array with two (or more) other arrays in C#?

    double[] d1 = new double[5];
    double[] d2 = new double[3];
    double[] dTotal = new double[8]; // I need this to be {d1 then d2}
    
  2. Another question: How do I concatenate C# arrays efficiently?

like image 457
Betamoo Avatar asked May 07 '10 12:05

Betamoo


People also ask

How do I combine two arrays?

The array_merge() function merges one or more arrays into one array. Tip: You can assign one array to the function, or as many as you like. Note: If two or more array elements have the same key, the last one overrides the others.

How do you concatenate an int array?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.


3 Answers

You could use CopyTo:

double[] d1 = new double[5];
double[] d2 = new double[3];
double[] dTotal = new double[d1.Length + d2.Length];

d1.CopyTo(dTotal, 0);
d2.CopyTo(dTotal, d1.Length);
like image 81
Julien Hoarau Avatar answered Oct 03 '22 21:10

Julien Hoarau


var dTotal = d1.Concat(d2).ToArray();

You could probably make it 'better' by creating dTotal first, and then just copying both inputs with Array.Copy.

like image 24
leppie Avatar answered Oct 03 '22 22:10

leppie


You need to call Array.Copy, like this:

double[] d1 = new double[5];
double[] d2 = new double[3];
double[] dTotal = new double[d1.length + d2.length];

Array.Copy(d1, 0, dTotal, 0, d1.Length);
Array.Copy(d2, 0, dTotal, d1.Length, d2.Length);
like image 26
SLaks Avatar answered Oct 03 '22 23:10

SLaks