1

What is the C# code to split an array from a given range. Eg:

int[] arr = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}

I want to split arr it into two arrays. One from 0th to 5th index and the other from 6th to 20th index.

In Java Arrays.copyOfRange() can be used for this process. What is the C# code for this?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
ANJ
  • 301
  • 1
  • 2
  • 14
  • 2
    `arr.Take(5).ToArray()` and `arr.Skip(5).ToArray()` – Dmitry Bychenko Apr 19 '17 at 08:36
  • Since this is a duplicate i've answered there: http://stackoverflow.com/a/43491049/284240 In general `Array.Copy` is more efficient than enumerating the array until you are at given indexes and create a new with `ToArray`. For small arrays this is micro-optimization. But since the ugly `Array.Copy` is hidden in an extension method you don't need to care about readable code. – Tim Schmelter Apr 19 '17 at 09:01

1 Answers1

6

Try using Linq:

 using System.Linq;

 ...

 int[] arr = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};

 int[] head = arr.Take(5).ToArray();
 int[] tail = arr.Skip(5).ToArray();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Thanks, what if I want to take elements from index 5 to index 10 and make a new array. Is there a direct method. – ANJ Apr 19 '17 at 08:52
  • @ANJ: To take items from index 5 to 10 just combine `Skip` and `Take`: `int[] middle = arr.Skip(5).Take(5).ToArray();` – Dmitry Bychenko Apr 19 '17 at 08:55