繁体   English   中英

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

[英]Changing a foreach loop to an if statement for reading a text file 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++;
}
}

如果你是指的一个变换foreachfor该测试的条件。 在代码中做出这一转变意味着你不需要设置x=0y=0之前,并增加他们内部foreach循环。

使用for会进行xy 初始化,条件和事后处理 ,并立即遍历数组。

许多人说您不讨厌StreamReader File.ReadAllLines 将为您打开和关闭文件

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);
        }
    }
}

您可以使用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

我认为,如果您尝试进一步减少代码,则会使您的意图变得模糊,没有任何好处。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM