Split an array into chunks of specific size in C#
This post will discuss how to split an array into chunks of a specific size in C#.
1. Using Skip() and Take()
The Take() method returns a specified number of elements from the beginning of a sequence, and the Skip() method skips the specified number of elements in a sequence. They can be used as follows to split an array into chunks of smaller arrays of a specific size.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
using System; using System.Linq; using System.Collections.Generic; public static class Extensions { public static IEnumerable<IEnumerable<T>> Split<T>(this T[] arr, int size) { for (var i = 0; i < arr.Length / size + 1; i++) { yield return arr.Skip(i * size).Take(size); } } } public class Example { public static void Main() { int[] arr = { 1, 2, 3, 4, 5 }; int size = 2; var arrays = arr.Split(size); foreach (var array in arrays) { Console.WriteLine(String.Join(", ", array)); } } } |
Output:
1, 2
3, 4
5
Another option is to use LINQ’s Select() method to split an array into equal length subarrays. The following code example shows how to use this with Skip() and Take() method:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; using System.Linq; using System.Collections.Generic; public static class Extensions { public static IEnumerable<IEnumerable<T>> Split<T>(this T[] arr, int size) { return arr.Select((s, i) => arr.Skip(i * size).Take(size)).Where(a => a.Any()); } } public class Example { public static void Main() { int[] arr = { 1, 2, 3, 4, 5 }; int size = 2; var arrays = arr.Split(size); foreach (var array in arrays) { Console.WriteLine(String.Join(", ", array)); } } } |
Output:
1, 2
3, 4
5
2. Using Enumerable.GroupBy Method
Alternatively, you can use the LINQ’s Enumerable.GroupBy method to group all items by the chunk size and convert each sequence to a new array. Here’s an example of its usage:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Linq; public class Example { public static void Main() { int[] arr = { 1, 2, 3, 4, 5 }; int size = 2; int i = 0; int[][] arrays = arr.GroupBy(s => i++ / size).Select(s => s.ToArray()).ToArray(); foreach (var array in arrays) { Console.WriteLine(String.Join(", ", array)); } } } |
Output:
1, 2
3, 4
5
That’s all about splitting an array into chunks of a specific size 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 :)