条件foreach循环c#

时间:2009-08-04 20:12:29

标签: c# loops conditional

我该怎么做? (c#)基本上,我希望能够排序,注释掉括号。但不是真的。我想我想要不按顺序关闭括号。这可能是不可能的。我显然可以在完全独立的if子句中实现它,但这会大大减轻我的代码。

PS:我正在尝试在foreach循环中放置“// do something”代码,或者为与具有不相关(对于foreach循环的参数)参数的单个实例放置代码,视情况而定。我希望这有助于澄清它。

伪代码我正在尝试做什么,如果你可以按顺序关闭括号):

我知道这不是有效代码附近的地方,正如我所说的那样是伪代码。

我还没看过第二篇文章,但第一篇文章(Sean Bright),谢谢你,但条件与条目数量无关(目录中总会有文件,无论我是否想要循环执行)

将// dosomething代码提取到函数中将起作用。我不确定我是如何忽视这一点的。我想我想知道是否有更简单的方法,但你是对的。谢谢。

if (isTrue)
{
    //START LOOP
    string [] fileEntries = Directory.GetFiles(LogsDirectory, SystemLogFormat);
    foreach(string fileName in fileEntries)
    {
       using (StreamReader r = new StreamReader(fileName))
       {
    /* The previous two blocks are not closed */
}
else
{
    using (StreamReader r = new StreamReader(SingleFileName))
    {
    /* The previous block is not closed */
}

// do all sorts of things

if (isTrue)
{
    /* Close the two unclosed blocks above */
        }
    }
}
else
{
    /* Close the unclosed block above */
    }
}

谢谢!

(缩进很奇怪,对不起,论坛在做什么)

3 个答案:

答案 0 :(得分:6)

为什么不这样做:

string [] fileEntries = null;

if (isTrue) {
    fileEntries = Directory.GetFiles(LogsDirectory, SystemLogFormat);
} else {
    fileEntries = new string [] { SingleFileName };
}

foreach(string fileName in fileEntries) {
    using (StreamReader r = new StreamReader(fileName)) {
        /* Do whatever */
    }
}

答案 1 :(得分:6)

将文件处理部分重构为一个单独的函数:

public void OriginalFunction() {
    if ( isTrue ) {
        string [] fileEntries = Directory.GetFiles(LogsDirectory, SystemLogFormat);
        foreach(string fileName in fileEntries) {
            ProcessFile(fileName);
        }
    } else {
        ProcessFile(SingleFileName);
    }

}

public void ProcessFile( string name ) {
    using (StreamReader r = new StreamReader(name))
    {
       // Do a bunch of stuff
    }
}

答案 2 :(得分:0)

使用条件来确定如何创建StreamReader,然后像往常一样在using()中传递它。

相关问题