C# Splitting An Array

You could use the following method to split an array into 2 separate arrays

public void Split<T>(T[] array, int index, out T[] first, out T[] second) {
  first = array.Take(index).ToArray();
  second = array.Skip(index).ToArray();
}

public void SplitMidPoint<T>(T[] array, out T[] first, out T[] second) {
  Split(array, array.Length / 2, out first, out second);
}

Use a generic split method:

public static void Split<T>(T[] source, int index, out T[] first, out T last)
{
    int len2 = source.Length - index;
    first = new T[index];
    last = new T[len2];
    Array.Copy(source, 0, first, 0, index);
    Array.Copy(source, index, last, 0, len2);
}

I also want to add a solution to split an array into several smaller arrays containing a determined number of cells.

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};
var splitArray = array.Split(2);

Have fun :)

Tags:

C#

Arrays