[Solved] How do I divide an array into separate arrays in C#?


I probably interpret your question wrong, as this seems too easy:

  1. Determine into how many arrays the source array will be divided. (totalCount / elementsPerArray)
  2. For each array:
    1. Determine how many elements to put in it. (elementsRemaining / arraysRemaining)
    2. Copy those elements to a new array.

In code:

private static List<string[]> DivideStrings(int expectedStringsPerArray, string[] allStrings)
{
    List<string[]> arrays = new List<string[]>();

    int arrayCount = allStrings.Length / expectedStringsPerArray;

    int elemsRemaining = allStrings.Length;
    for (int arrsRemaining = arrayCount; arrsRemaining >= 1; arrsRemaining--)
    {
        int elementCount = elemsRemaining / arrsRemaining;

        string[] array = CopyPart(allStrings, elemsRemaining - elementCount, elementCount);
        arrays.Insert(0, array);

        elemsRemaining -= elementCount;
    }

    return arrays;
}

 

private static T[] CopyPart<T>(T[] array, int index, int length)
{
    T[] newArray = new T[length];
    Array.Copy(array, index, newArray, 0, length);
    return newArray;
}

When used like this:

const int count = 23;
const int estimate = 7;
string[] strings = Enumerable.Range(1, count).Select(s => s.ToString()).ToArray();
var list = DivideStrings(estimate, strings);
foreach (var arr in list)
    Console.WriteLine(String.Join(" ", arr));

It prints:

1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23

0

solved How do I divide an array into separate arrays in C#?