将foreach循环更改为if语句以读取文本文件C#

时间:2015-03-22 10:59:44

标签: c#

好的,所以这是我的代码,但我想弄清楚如何将这个foreach循环更改为if语句。我一直试图通过自己解决这个问题,但它似乎并没有像我想要的那样工作。因此,如果有人可以提供帮助,那将非常感激。就像额外的东西一样,我仍然是C#的菜鸟。 :)

// Used to make sure that the script can read the text file
    using (StreamReader sr = new StreamReader ("Maze.txt")) 
    {
        lineArray = File.ReadAllLines("Maze.txt");

        // Access one line at a time
        foreach (string line in lineArray)
        { 
            // Reset X axis for each line of the file
            int x = 0;

            // Access each character in the file
            foreach (char c in line)
            {
            string currentPosition = c.ToString();
            newFilePosition = Convert.ToInt32(currentPosition);

            if (newFilePosition == 1)
            {
                // Create a cube on the X axis
                NewCubePosition = new Vector3 (x, y, 0);
                Instantiate (g_mazeCubes, NewCubePosition, Quaternion.identity);
            }
            // Loop until X axis is done
            x++;
        }
    // Loop until Y axis is done
    y++;
}
}

2 个答案:

答案 0 :(得分:2)

如果您要引导将foreach转换为测试条件的for。在代码中进行此转换意味着您需要先设置x=0y=0并在foreach增加循环。

使用for,您将xy initialization, the condition, and the afterthought,并立即迭代数组。

许多人说你不会StreamReaderFile.ReadAllLines opens and close the file for you

lineArray = File.ReadAllLines("Maze.txt");

// Access one line at a time
for (y = 0; y < lineArray.Count(); y++)
{
    string line = lineArray[y];

    // Access each character in the file
    for (int x = 0 ; x < line.Count(); x++)
    {
        char c = line[x];
        string currentPosition = c.ToString();
        newFilePosition = Convert.ToInt32(currentPosition);

        if (newFilePosition == 1)
        {
            // Create a cube on the X axis
            NewCubePosition = new Vector3 (x, y, 0);
            Instantiate (g_mazeCubes, NewCubePosition, Quaternion.identity);
        }
    }
}

答案 1 :(得分:0)

您可以使用一些LINQ来减少代码,但我不认为您可以做任何事情来摆脱内循环。

var lineArray = File.ReadAllLines("Maze.txt");

for (var y = 0; y < lineArray.Length; y++)
{
    foreach (var c in lineArray[y].Select((value, i) => new { Character = value, Index = i })
                                  .Where(x => Convert.ToInt32(x.Character) == 1))
    {
        Instantiate(g_mazeCubes, new Vector3(c.Index, y, 0), Quaternion.identity);
    }
}

(您也不需要StreamReader

在我看来,如果你试图进一步减少代码,你将无意中混淆意图。