Mike
Mike

Reputation: 3284

Copy arrays from specific indexes

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};

Upvotes: 4

Views: 2742

Answers (3)

CrazyDart
CrazyDart

Reputation: 3801

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();

Upvotes: 0

David Yaw
David Yaw

Reputation: 27874

Is this what you're looking for?

Array.Copy(source, 0 /*start loc*/, destination, 3 /*start loc*/, 2 /*count*/);

Upvotes: 8

Mark Byers
Mark Byers

Reputation: 839074

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

source.CopyTo(destination, 3);

Upvotes: 7

Related Questions