5
  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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Betamoo
  • 14,964
  • 25
  • 75
  • 109
  • 4
    If you have arrays that you need to change or mix and match like this, you should probably be use a generic List instead. – Joel Coehoorn May 07 '10 at 13:09
  • possible duplicate of [How do I concatenate two arrays in C#?](http://stackoverflow.com/questions/1547252/how-do-i-concatenate-two-arrays-in-c) – Matt Sach Aug 08 '13 at 14:37

4 Answers4

9

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Julien Hoarau
  • 48,964
  • 20
  • 128
  • 117
6
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.

leppie
  • 115,091
  • 17
  • 196
  • 297
  • 1
    This will be inefficient for large arrays. – SLaks May 07 '10 at 12:57
  • @SLaks: That's why I added the little extra bit, but even for meduim size arrays (up to 10000 elements), you would probably not even notice the difference. Also Enumerable may provide a fast option for `Concat` if both are arrays (will have to look at source to confirm). Update: It does NOT have a fast option for anything. – leppie May 07 '10 at 13:00
5

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);
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
-1
using System.Linq;

int[] array1 = { 1, 3, 5 };
int[] array2 = { 0, 2, 4 };

// Concat array1 and array2.
var result1 = array1.Concat(array2).ToArray();
pinckerman
  • 4,115
  • 6
  • 33
  • 42
Roland
  • 535
  • 4
  • 2