This post will discuss how to get a slice of an array in C#.

1. Using ArraySegment<T> Struct

The ArraySegment<T> structure delimits the specified range of the elements in the specified array. The following code example uses an ArraySegment<T> structure to return a portion of an integer array.

Download  Run Code

2. Using LINQ

We can use the combination of LINQ’s Skip() and Take() methods to get a slice of an array. The Enumerable.Skip() method returns a copy of the sequence with a specified number of elements removed, and the Enumerable.Take() method returns the specified number of elements from the start of a sequence. Note that this approach is very slow as compared to the Array.Copy() method.

Download  Run Code

3. Using range notation

Starting from C# 8, we can use the range notation .. to get a slice of an array. It takes the start and the end of a range as its operands, where the start of the range is inclusive and the end of the range is exclusive. The following code example demonstrates this:

Download  Run Code

That’s all about getting a slice of an array in C#.