How can I split an array into n parts?
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!
using Linq
public List<List<byte>> SplitToSublists(List<byte> source)
{
return source
.Select((x, i) => new { Index = i, Value = x })
.GroupBy(x => x.Index / 100)
.Select(x => x.Select(v => v.Value).ToList())
.ToList();
}
Simply use it
var sublists = SplitToSublists(lst);
This to have list of lists
array.Select((s,i) => array.Skip(i * 2).Take(2)).Where(a => a.Any())
Or this to have list of items
array.SelectMany((s,i) => array.Skip(i * 2).Take(2)).Where(a => a.Any())