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?

2
  • 2
    arr.Take(5).ToArray() and arr.Skip(5).ToArray() Commented Apr 19, 2017 at 8:36
  • Since this is a duplicate i've answered there: 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. Commented Apr 19, 2017 at 9:01

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

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: To take items from index 5 to 10 just combine Skip and Take: int[] middle = arr.Skip(5).Take(5).ToArray();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.