数组列表到维数组

时间:2017-01-19 18:47:50

标签: c# arrays


我有以下问题:
我的教授有一个.txt文件,其中包含不同的数字。
每个数字都在另一行。此文件中没有其他内容。
这些数字代表坐标,例如。 first line = first x coord。,second line = first y coord。等等。我们可能不会使用LINQ。

所以我的问题是:如何将这些数字转换为如下所示的二维数组?

coordArray[0,0] = line1 of textfile (x1)
coordArray[0,1] = line2 (y1)
coordArray[1,0] = line3 (x2)

我已经尝试了以下但没有成功:

        string path = @"C:\coords.txt";
        int lines = (File.ReadAllLines(path).Count())/2;

        List<double> xy = new List<double>();
        using (StreamReader r = new StreamReader(path))
        {
            string coord;
            while ((coord = r.ReadLine()) != null)
            {
                xy.Add(double.Parse(coord));
            }
        }

        double[,] coordArray = new double[lines, 2];
        for(int i = 0; i<lines; i+=2)
        {
            for(int j = 0; j<lines; j++)
            {
                coordArray[j, 0] = xy[i];
                coordArray[j, 1] = xy[i + 1];
            }
        }

1 个答案:

答案 0 :(得分:2)

您可以尝试将示例中的最后两个for周期更改为:

for(int i = 0; i<lines; i+=2)
{
    coordArray[i/2, 0] = xy[i];
    coordArray[i/2, 1] = xy[i + 1];
}

具有两个for周期的原始解决方案在所有行上迭代两次,而您只需要遍历它们一次但在每次迭代中处理两行。

注意:当行数为偶数时,程序将抛出异​​常