views:

156

answers:

3

1- How to smartly initialize an Array with 2 (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 to concatenate C# arrays efficiently?

Thanks

+3  A: 
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
This will be inefficient for large arrays.
SLaks
@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
+2  A: 

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
+6  A: 

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);
madgnome
Msdn is a little bit unclear, but the index parameter specifies the index in the destination array.
madgnome
You need d1.length - 1, I believe
Rubys
@madgnome: You're right; I misunderstood. Sorry. @Rubys: No, you don't.
SLaks
First I copy 5 doubles from d1 to dTotal. Then I copy d2 to dTotal starting in index 5. If I use `d1.Lenght - 1` I'll start at index 4 and I'll lost the last value of d1.
madgnome