Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a copy of integer array [duplicate]

Tags:

c#

Possible Duplicate:
C#: Any faster way of copying arrays?

I have an integer array

int[] a;

I want to assign a copy of it(not reference) to

int[] b;

what is the easier way to do it?

like image 454
william007 Avatar asked Feb 01 '13 17:02

william007


People also ask

How do you create a duplicate array?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.

Which method of an array creates a duplicate copy?

Use the clone method of the array.

How do you copy an entire array?

The System ClassarrayCopy(). This copies an array from a source array to a destination array, starting the copy action from the source position to the target position until the specified length. The number of elements copied to the target array equals the specified length.


2 Answers

You can use the native Clone method, try something like this:

int[] b = (int[])a.Clone();

Other options are, using linq:

using System.Linq;

// code ...
int[] b = a.ToArray();

And copying the array

int[] b = new int[a.Length];
a.CopyTo(b, 0);
like image 93
Felipe Oriani Avatar answered Oct 21 '22 02:10

Felipe Oriani


I think simplest way would be

int[] b = a.ToArray();
like image 33
I4V Avatar answered Oct 21 '22 01:10

I4V