Split Array in C#
Given an integer array and split size, split the array into multiple sub-arrays where each array is of length size!
List of Lists
To split the input array, let's create a List
of List<int>
and call it subArray. For each integer in the source array, we need to go through a series of steps. First, we are going to retrieve the last item in the subArray object. For the first time the loop runs, the last item will be null
. So, we are going to initialize a new List<int>
and add the current integer to it and add the list object to subArray list.
In the next iteration, we will attempt to retrieve the last item in the subArray object. This time the last object is not null
, Now, If the number of integers in List<int>
is less than the split size, the else block will run and the current integer will add to the current list, otherwise, a new list will be initialized.
using System.Collections.Generic;
public static List<List<int>> SplitArray(int[] source, int size)
{
var subArray = new List<List<int>>();
foreach (var item in source)
{
var last = subArray.Count == 0 ? null : subArray[^1];
if (last == null || last.Count == size)
{
subArray.Add(new List<int> {item});
}
else
{
last.Add(item);
}
}
return subArray;
}
using System.Collections.Generic;
using System.Linq;
public static int[][] SplitArray(int[] source, int size)
{
var subArray = new List<List<int>>();
foreach (var item in source)
{
var last = subArray.Count == 0 ? null : subArray[^1];
if (last == null || last.Count == size)
{
subArray.Add(new List<int> { item });
}
else
{
last.Add(item);
}
}
return subArray.Select(x => x.ToArray()).ToArray();
}
Jagged Array
The List<T>
class uses an array whose size is dynamically increased when you add objects to it. The list resizing process is a costly operation. Also, using ToArray()
method result in a negative performance impact.
To split an array, we could directly use a jagged array. In this case, we need to find the number of sub-arrays and the number of items in each sub-array. To copy elements of the source array to sub-array, we use the Array.Copy()
method. As shown below, we invoked Array.Copy()
, with 5 arguments—the source array, starting index in the source array, the destination sub-array, starting index in the sub-array, and the length.
public static int[][] SplitArray(int[] source, int size)
{
// Number of sub-arrays, round up to the nearest integer.
var dim1 = (int) Math.Ceiling(source.Length / (float) size);
// Declare the source.
var subArray = new int[dim1][];
var index = 0;
for (var i = 0; i < dim1; i++)
{
// Number of elements left in the original source.
var remainItems = source.Length - index;
// Number of elements in each sub-arrays.
var dim2 = remainItems >= size ? size : remainItems;
subArray[i] = new int[dim2];
// Copy from original source to sub-source
Array.Copy(source, index, subArray[i], 0, dim2);
index += dim2;
}
return subArray;
}
LINQ Operators
We can use LINQ operators to split an array. We need to group all items by the split size and create new sub-arrays afterward. The caveat is that although this implementation is more brief, it is a quite costly operation.
using System.Linq;
public static int[][] SplitArray(int[] source, int size)
{
return source
.Select((x, i) => new {Value = x, Index = i})
.GroupBy(x => x.Index / size)
.Select(x => x.Select(v => v.Value).ToArray())
.ToArray();
}
Print Jagged Array
We can print the jagged array using two foreach loops, as shown below.
public static void PrintJaggedArray(int[][] jagged)
{
foreach (var arr in jagged)
{
foreach (var item in arr)
{
Console.Write($"{item}\t");
}
Console.WriteLine();
}
}
You can download the source code on Github.