把数组分批遍历到一个新数组,请给出csharp代码
时间: 2024-05-06 17:19:24 浏览: 66
以下是分批遍历数组并生成新数组的 C# 代码:
```
public static T[] BatchedArray<T>(T[] sourceArray, int batchSize)
{
int numberOfBatches = (int)Math.Ceiling((double)sourceArray.Length / batchSize);
T[] resultArray = new T[numberOfBatches];
for (int i = 0; i < numberOfBatches; i++)
{
int currentIndex = i * batchSize;
T[] currentBatch = new T[Math.Min(batchSize, sourceArray.Length - currentIndex)];
for (int j = 0; j < currentBatch.Length; j++)
{
currentBatch[j] = sourceArray[currentIndex + j];
}
resultArray[i] = currentBatch;
}
return resultArray;
}
```
使用方法:
```
int[] sourceArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int batchSize = 3;
int[][] resultArray = BatchedArray(sourceArray, batchSize);
// Output: {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10}}
Console.WriteLine(string.Join(", ", resultArray.Select(batch => $"{{{string.Join(", ", batch)}}}")));
```
阅读全文