gpt4 book ai didi

c# - 一个大数组如何拆分成更小的数组?

转载 作者:太空狗 更新时间:2023-10-30 00:02:24 25 4
gpt4 key购买 nike

给定一个大数组,如何将其拆分为较小的数组,并将较小数组的大小指定为方法的参数?

例如,给定数字,Split 的实现方式是什么?

int[] numbers = new int[7845];

int[][] sectionedNumbers = numbers.Split(1000);

sectionedNumbers.Length; //outputs 8
sectionedNumbers[7].Length; //outputs 845

最佳答案

您可以使用扩展方法来实现:

using System;

static class Program
{
static T[][] Split<T>(this T[] arrayIn, int length)
{
bool even = arrayIn.Length%length == 0;
int totalLength = arrayIn.Length/length;
if (!even)
totalLength++;

T[][] newArray = new T[totalLength][];
for (int i = 0; i < totalLength;++i )
{
int allocLength = length;
if (!even && i == totalLength - 1)
allocLength = arrayIn.Length % length;

newArray[i] = new T[allocLength];
Array.Copy(arrayIn, i * length, newArray[i], 0, allocLength);
}
return newArray;
}

static void Main(string[] args)
{
int[] numbers = new int[8010];
for (int i = 0; i < numbers.Length; ++i)
numbers[i] = i;

int[][] sectionedNumbers = numbers.Split(1000);

Console.WriteLine("{0}", sectionedNumbers.Length);
Console.WriteLine("{0}", sectionedNumbers[7].Length);
Console.WriteLine("{0}", sectionedNumbers[1][0]);
Console.WriteLine("{0}", sectionedNumbers[7][298]);
Console.ReadKey();
}
}

这打印:

9
1000
1000
7298

关于c# - 一个大数组如何拆分成更小的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1616144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com