我可能错误地解释了您的问题,因为这似乎太容易了:
- 确定将源数组划分为多少个数组。( totalCount / elementsPerArray )
- 对于每个数组:
- 确定要放入多少元素。(元素剩余/数组剩余)
- 将这些元素复制到一个新数组中。
在代码中:
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;
}
像这样使用时:
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));
它打印:
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23