How do I clone a range of array elements to a new array?

前端 未结 25 1009
北海茫月
北海茫月 2020-11-22 16:07

I have an array X of 10 elements. I would like to create a new array containing all the elements from X that begin at index 3 and ends in index 7. Sure I can easily write a

25条回答
  •  北海茫月
    2020-11-22 16:52

    How about useing Array.ConstrainedCopy:

    int[] ArrayOne = new int[8] {1,2,3,4,5,6,7,8};
    int[] ArrayTwo = new int[5];
    Array.ConstrainedCopy(ArrayOne, 3, ArrayTwo, 0, 7-3);
    

    Below is my original post. It will not work

    You could use Array.CopyTo:

    int[] ArrayOne = new int[8] {1,2,3,4,5,6,7,8};
    int[] ArrayTwo = new int[5];
    ArrayOne.CopyTo(ArrayTwo,3); //starts copy at index=3 until it reaches end of
                                 //either array
    

提交回复
热议问题