I have a list of bytes and I want to split this list into smaller parts.
var array = new List<byte> {10, 20, 30, 40, 50, 60};
This list has 6 cells. For example, I want to split it into 3 parts containing each 2 bytes.
I have tried to write some for loops and used 2D arrays to achieve my purpose but I don't know it is a correct approach.
byte[,] array2D = new byte[window, lst.Count / window];
var current = 0;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array2D[i, j] = lst[current++];
}
}
A nice way would be to create a generic/extension method to split any array. This is mine:
/// <summary>
/// Splits an array into several smaller arrays.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
/// <param name="array">The array to split.</param>
/// <param name="size">The size of the smaller arrays.</param>
/// <returns>An array containing smaller arrays.</returns>
public static IEnumerable<IEnumerable<T>> Split<T>(this T[] array, int size)
{
for (var i = 0; i < (float)array.Length / size; i++)
{
yield return array.Skip(i * size).Take(size);
}
}
Moreover, this solution is deferred. Then, simply call Split(size)
on your array.
var array = new byte[] {10, 20, 30, 40, 50, 60};
var splitArray = array.Split(2);
As requested, here is a generic/extension method to get a square 2D arrays from an array:
/// <summary>
/// Splits a given array into a two dimensional arrays of a given size.
/// The given size must be a divisor of the initial array, otherwise the returned value is <c>null</c>,
/// because not all the values will fit into the resulting array.
/// </summary>
/// <param name="array">The array to split.</param>
/// <param name="size">The size to split the array into. The size must be a divisor of the length of the array.</param>
/// <returns>
/// A two dimensional array if the size is a divisor of the length of the initial array, otherwise <c>null</c>.
/// </returns>
public static T[,]? ToSquare2D<T>(this T[] array, int size)
{
if (array.Length % size != 0) return null;
var firstDimensionLength = array.Length / size;
var buffer = new T[firstDimensionLength, size];
for (var i = 0; i < firstDimensionLength; i++)
{
for (var j = 0; j < size; j++)
{
buffer[i, j] = array[i * size + j];
}
}
return buffer;
}
Have fun!