List to two-dimensional Array

大憨熊 提交于 2021-01-28 02:00:24

问题


How would one go about converting a list of integers to a two-dimensional array?

List<int> integerList = new List<int>();
integerList.Add(1);
integerList.Add(2);
...
integerList.Add(250000);
int[,] integerArray = new int[500,500];

//fill integerArray with integerList values here

Target output should be in rows, filling x from 0-499 then incrementing y by 1 and repeat. integerArray[x,y]


回答1:


Try this:

int i = 0;
foreach(var number in integerList)
{
    integerArray[i % 500, (int)(i / 500)] = number;
    i++;
}

If you want to the number to increment through the column first, just transpose the mod and div operations inside the array.




回答2:


You can just use a list of arrays, but that won't guarantee the length of the items:

List l = new List<int[]>();
l.Add(new int[500]);


来源:https://stackoverflow.com/questions/7073343/list-to-two-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!