Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy part of an array to another array in C#?

Tags:

arrays

c#

People also ask

How do I copy part of an array to another array?

The Array. Copy() method in C# is used to copy section of one array to another array. Array. Copy(src, dest, length);

How do you copy part of an array?

JavaScript Arrays Copy part of an ArrayThe slice() method returns a copy of a portion of an array.

How do you copy a half array?

copyOf() method. Arrays. copyOfRange() is used to copy a specified range of an array. If the starting index is not 0, you can use this method to copy a partial array.

How do you copy a string from an array to another array in C?

strcpy can be used to copy one string to another. Remember that C strings are character arrays. You must pass character array, or pointer to character array to this function where string will be copied. The destination character array is the first parameter to strcpy .


int[] b = new int[3];
Array.Copy(a, 1, b, 0, 3);
  • a = source array
  • 1 = start index in source array
  • b = destination array
  • 0 = start index in destination array
  • 3 = elements to copy

See this question. LINQ Take() and Skip() are the most popular answers, as well as Array.CopyTo().

A purportedly faster extension method is described here.


int[] a = {1,2,3,4,5};

int [] b= new int[a.length]; //New Array and the size of a which is 4

Array.Copy(a,b,a.length);

Where Array is class having method Copy, which copies the element of a array to b array.

While copying from one array to another array, you have to provide same data type to another array of which you are copying.


Note: I found this question looking for one of the steps in the answer to how to resize an existing array.

So I thought I would add that information here, in case anyone else was searching for how to do a ranged copy as a partial answer to the question of resizing an array.

For anyone else finding this question looking for the same thing I was, it is very simple:

Array.Resize<T>(ref arrayVariable, newSize);

where T is the type, i.e. where arrayVariable is declared:

T[] arrayVariable;

That method handles null checks, as well as newSize==oldSize having no effect, and of course silently handles the case where one of the arrays is longer than the other.

See the MSDN article for more.