tags:

views:

42

answers:

3

Hi,

How can I copy an array of values to a destination array starting from a specific index without looping?

For example,if I have an array with 2 values, I have to copy those two elements to another array which has a capacity of 5 starting from index 3?

 double[] source = new double[] {1, 2};
 double[] destination = new double[5]{0,0,0,0,0};
 //How to perform this copy?
 double[] result = new double[5] {0, 0, 0, 1, 2};
+7  A: 

Use Array.CopyTo or the static method Array.Copy.

source.CopyTo(destination, 3);
Mark Byers
Copy of david yaw's... his came first, i have to vote for his.
Richard J. Ross III
@Richard J. Ross III - What has "first" got to do with it? Vote for best answer rather than "first". You do know you can vote for as many answers as you want, right?
Oded
Richard J. Ross III
@Richard J. Ross III - SO lets you edit answers (and questions) to make them better. Many people post an initial answer then make it better - which is why you should let the dust settle before voting...
Oded
+8  A: 

Is this what you're looking for?

Array.Copy(source, 0 /*start loc*/, destination, 3 /*start loc*/, 2 /*count*/);
David Yaw
A: 
double[] source = new double[] {1, 2};
 double[] destination = new double[5]{0,0,0,0,0};
 //How to perform this copy?
ArrayList result = new ArrayList();
result.AddRange(source);
result.AddRange(destination);
destination = result.ToArray();
CrazyDart
I dont think that this is the answer he was looking for, as it doesn't quite only do that from the specified indices
Richard J. Ross III