c# - C# 将 1D 数组拆分为每 N 个值的 2D 数组
问题描述
我有一个一维整数数组:
int[] array = { 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31, 32,33, 34,40,41,42,43, 44};
我想将此一维数组划分为 4 行 5 列的 2D 数组,其中前 5 个值进入第 1 行,接下来的 5 个值进入第 2 行,依此类推。最终结果应如下所示:
数组2D:
[[10, 11, 12, 13, 14]
[20, 21, 22, 23, 24]
[30, 31, 32, 33, 34]
[40, 41, 42, 43, 44]]
实际上,数组会更长(可能超过 100 行),但列数为 5,行数可被 5 整除。例如,我已经简化了。这是我到目前为止所尝试的:
int[] array = { 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31, 32,33, 34,40,41,42,43, 44};
int[,] array2D = new int[(array.Length/5),5];
int count_0 = 1;
int count_1 = 1;
int count_2 = 1;
int count_3 = 1;
int count_4 = 1;
for (int i = 0; i < array.Length; i++)
{
if (i < 5)
{
// works for the first 5 values:
array2D[0, i] = array[i];
}
// I tried this approach for the rest where I try to say that if Im at index 5,
//and every 5th element from here, append to it to index[i,0] of array2D and so on.
// This do not work, and is what I need help with.
else if (i >= 5 && i % 5 == 0)
{
array2D[count_0, 0] = array[i];
count_0++;
}
else if (i >= 6 && i % 5 == 0)
{
array2D[count_1, 1] = array[i];
count_1++;
}
else if (i >= 7 && i % 5 == 0)
{
array2D[count_2, 2] = array[i];
count_2++;
}
else if (i >= 8 && i % 5 == 0)
{
array2D[count_3, 3] = array[i];
count_3++;
}
else if (i >= 9 && i % 5 == 0)
{
array2D[count_4, 4] = array[i];
count_4++;
}
}
当然,对于这个例子,我可以说if > 5 && <10 {append to array2D}
等等if > 10 && <15 {append to array2D}
,但我想要一些适用于数百个值的大型数组的东西。如果有人有更聪明的方法来做到这一点,请告诉我。
感谢您的任何帮助!
解决方案
您可以只计算索引:
for(int i=0;i<array.Length;i++)
array2D[i/5, i%5] = array[i];
推荐阅读
- javascript - 在选择大范围的工作簿中调用 getSelectedRanges 方法时,桌面 Excel 挂起
- c# - C# api 给出错误“'ObjectContent`1' 类型未能序列化内容类型 'application/xml; charset=utf-8' 的响应正文。”
- mongodb - 如何检查所有数据库的 mongodb 索引,而不是按集合搜索?
- swift - 导出 Xcode 注释生成文档
- php - 为什么在 phpmyadmin 上登录提交后出现 403 错误
- android - 如何实现动态 API 处理?
- laravel - 如何以laravel方式从远距离关系中获取计数?
- c# - 如何正确地从 ViewModel 调用 Dialog?
- web - 利用浏览器缓存 - 我已启用此功能,但 GT Metrix 未显示
- c# - DialogOpenedAttached 中的“TypeConverter 无法从 System.String 转换”