条件foreach循环c#

1 c# conditional loops

我怎样才能做到这一点?(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 */
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

(缩进很奇怪,抱歉,论坛在做)

Sea*_*ght 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 */
    }
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*lje 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
    }
}
Run Code Online (Sandbox Code Playgroud)