Get slice of an array in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { int[] arr = { 1, 2, 3, 4, 5 }; int start = 1, end = 3; var segment = new ArraySegment<int>(arr, start, end); Console.WriteLine(String.Join(", ", segment)); // 2, 3, 4 } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; public class Example { public static void Main() { int[] arr = { 1, 2, 3, 4, 5 }; int start = 1, end = 3; var slice = arr.Skip(start).Take(end - start + 1); Console.WriteLine(String.Join(", ", slice)); // 2, 3, 4 } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; public class Example { public static void Main() { int[] arr = { 1, 2, 3, 4, 5 }; int start = 1, end = 3; var slice = arr[start..(end + 1)]; Console.WriteLine(String.Join(", ", slice)); // 2, 3, 4 } } |
That’s all about getting a slice of an array in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)