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

时间:2009-04-09 07:50:00

标签: c# arrays

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

考虑一下我

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

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

就像我将start index设为1并将end index设为3一样,元素2,3,4应该被复制到新数组中。

5 个答案:

答案 0 :(得分:253)

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

答案 1 :(得分:17)

this question。 LINQ Take()和Skip()是最受欢迎的答案,以及Array.CopyTo()。

据称速度更快extension method is described here

答案 2 :(得分:2)

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数组。

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

答案 3 :(得分:1)

注意:我发现此问题正在寻找如何 调整 现有数组的答案中的一个步骤。

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

对于其他人发现这个问题寻找同样的事情,这很简单:

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

其中 T 是类型,即声明arrayVariable的地方:

T[] arrayVariable;

该方法处理空检查,以及newSize == oldSize无效,当然还默默处理其中一个数组长于另一个数组的情况。

有关详情,请参阅the MSDN article

答案 4 :(得分:0)

如果您想要实现自己的 Array.Copy 方法。

通用类型的静态方法。

 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();
            }
        }
相关问题