从文件读取值到multidimensionnal数组

时间:2015-05-06 15:36:27

标签: c# arrays

我想从外部数据文件中读取文件,将它们粘贴到数组中以导入Unity3D。 所以我开始了:

int [,] positionTab = new int[noLoc,3];

StreamReader sr = new StreamReader(myTextFile);
while((line = sr.ReadLine()) != null)//read line by line up to the end
{
    if (line.Contains("confTrain1"))
    {
        locationTrain1 = RetrieveValueInDataFile.locationTrain(line);
    }
    else if (line.Contains("confTrain2"))
    {
        locationTrain2 = RetrieveValueInDataFile.locationTrain(line);
    }
    else 
    {
        distanceBetweenThem =RetrieveValueInDataFile.distBetweenTrain(line);
    }

我想知道如下:

int [,] locations = new int [noLoc, 3]
{
{locationTrain1, locationTrain2, distanceBetweenThem}
{locationTrain1, locationTrain2, distanceBetweenThem}
{etc}
}

问题是我不知道如何在StreamReader中执行此操作。我的意思是,我如何添加两个位置和距离(语法)?

1 个答案:

答案 0 :(得分:0)

构造数组时只能使用这种数组初始化语法。

如果您需要设置现有数组的值(如示例中所示) - 请使用索引:

int [,] locations = new int [noLoc, 3]
var rowIndex = 0;
using(StreamReader sr = new StreamReader(myTextFile))
{
    while(
      rowIndex < noLoc && // if using array you have to read no more than allocated
       (line = sr.ReadLine()) != null)
    {
      locations[rowIndex,0] = locationTrain1;
      locations[rowIndex,1] = locationTrain2;
      locations[rowIndex,2] = distanceBetweenThem;
      rowIndex++;
    }
}

请注意,定义包含此值的类可能会更好,并在读取它们时将它们存储在List中。