如何复制一个数组的一部分到另一个数组在 C # ?

如何将数组的一部分复制到另一个数组?

考虑一下

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

现在,如果我给出数组 a的起始索引和结束索引,它应该被复制到另一个数组。

如果我将开始索引设置为1,结束索引设置为3,那么元素2、3、4应该被复制到新数组中。

213274 次浏览
int[] b = new int[3];
Array.Copy(a, 1, b, 0, 3);
  • A = 源数组源数组
  • 1 = 源数组中的开始索引
  • B = 目标数组
  • 0 = 目标数组中的开始索引
  • 3 = 要复制的元素

参见 这个问题.LINQTake ()和 Skip ()是最流行的答案,还有 Array.CopyTo ()。

据说是更快的 本文介绍了可拓方法

注意: 我发现这个问题在寻找如何使用现有数组 调整大小的答案中的一个步骤。

所以我想我应该在这里添加这些信息,以防其他人正在搜索如何进行远程拷贝,作为调整数组大小问题的部分答案。

对于那些发现这个问题的人来说,寻找和我一样的东西,答案很简单:

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

其中 T是类型,即数组变量声明为:

T[] arrayVariable;

该方法可以处理 null 检查,newSize = = oldSize 没有任何效果,当然还可以静默地处理其中一个数组比另一个数组长的情况。

有关更多信息,请参见 MSDN 文章

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

其中 Array 是具有 Copy 方法的类,该方法将数组的元素复制到 b 数组。

在从一个数组复制到另一个数组时,必须为正在复制的另一个数组提供相同的数据类型。

如果您想实现自己的 数组,收到方法。

泛型的静态方法。

 static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
{
long totaltraversal = sourceIndex + copyNoOfElements;
long sourceArrayLength = sourceArray.Length;


//to check all array's length and its indices properties before copying
CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
for (long i = sourceIndex; i < totaltraversal; i++)
{
destinationArray[destinationIndex++] = sourceArray[i];
}
}

边界法实现。

private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
{
if (sourceIndex >= sourceArray.Length)
{
throw new IndexOutOfRangeException();
}
if (copyNoOfElements > sourceArrayLength)
{
throw new IndexOutOfRangeException();
}
if (destinationArray.Length < copyNoOfElements)
{
throw new IndexOutOfRangeException();
}
}

在 C # 8 + 中,你可以使用范围。

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

Https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges