This post will discuss how to get a subarray of an array between specified indices in C#.

1. Using Array.Copy() method

A simple solution is to create a new array of required length and then call the Array.Copy() method to copy the required range of elements from the given array to the new array.

Download  Run Code

2. Using Enumerable.Skip with Enumerable.Take

The System.Linq.Enumerable.Skip() method bypasses the specified number of items in a sequence. It then returns the remaining elements, and the System.Linq.Enumerable.Take() method returns a specified number of contiguous elements from the start of a sequence.

The following code example demonstrates how the combination of Skip and Take can get subarray from the array.

Download  Run Code

3. Using ArraySegment<T> Struct

To get a subarray, we can initialize a new instance of the ArraySegment<T> structure that delimits the specified range of the elements in the specified array.

Download  Run Code

4. Using List.GetRange() method

Here, the idea is to convert the array into a list and then use its GetRange() method to get elements between the desired range. Then, we can use the ToArray() method to convert the list into an array.

The following example demonstrates how we can use the GetRange() method to get a slice of an array.

Download  Run Code

That’s all about getting a subarray of an array between specified indices in C#.