Split an array into two arrays in C#
This post will discuss how to split an array into two equal-size parts in C#. If the number of elements is odd, the first half should accommodate the extra element.
1. Using Linq
The Enumerable.Take() method returns a supplied number of elements from the start of a sequence and the Enumerable.Skip() method skips the supplied number of items in a sequence. It can be used as follows to split an array into two equal-size parts:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; public class Example { public static void Main() { int[] arr = { 1, 2, 3, 4, 5 }; int mid = (arr.Length + 1) / 2; int[] firstHalf = arr.Take(mid).ToArray(); int[] secondHalf = arr.Skip(mid).ToArray(); Console.WriteLine(String.Join(", ", firstHalf)); // 1, 2, 3 Console.WriteLine(String.Join(", ", secondHalf)); // 4, 5 } } |
2. Using Array.Copy method
The Array.Copy method copies a range of elements from an array to another array. It can be used as follows to copy the first half and the second half from the original array to new arrays:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; public class Example { public static void Main() { int[] arr = { 1, 2, 3, 4, 5 }; int mid = (arr.Length + 1) / 2; int[] firstHalf = new int[mid]; int[] secondHalf = new int[arr.Length - mid]; Array.Copy(arr, 0, firstHalf, 0, mid); Array.Copy(arr, mid, secondHalf, 0, secondHalf.Length); Console.WriteLine(String.Join(", ", firstHalf)); // 1, 2, 3 Console.WriteLine(String.Join(", ", secondHalf)); // 4, 5 } } |
3. Using Range Notation
Since C# 8, you can use the range notation .., which specifies the start and end of a range as its operands. The start of the range is inclusive and the end of the range is exclusive. The following code example shows splits an array using ranges that are open-ended at the start and the end:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { int[] arr = { 1, 2, 3, 4, 5 }; int mid = (arr.Length + 1) / 2; int[] firstArray = arr[..mid]; int[] secondArray = arr[mid..]; Console.WriteLine(String.Join(", ", firstArray)); // 1, 2, 3 Console.WriteLine(String.Join(", ", secondArray)); // 4, 5 } } |
That’s all about splitting an array into two equal-size parts 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 :)