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

前端 未结 25 1407
北海茫月
北海茫月 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:37

    You can use Array.Copy(...) to copy into the new array after you've created it, but I don't think there's a method which creates the new array and copies a range of elements.

    If you're using .NET 3.5 you could use LINQ:

    var newArray = array.Skip(3).Take(5).ToArray();
    

    but that will be somewhat less efficient.

    See this answer to a similar question for options for more specific situations.

提交回复
热议问题