如何在C#中的if语句中打破List <T> .ForEach()循环

Gga*_*Gga 1 c# foreach for-loop

我想List<T>.ForEach()if语句中跳过循环的迭代.

我有代码:

        instructions.ForEach(delegate(Instruction inst)
        {                
            if (!File.Exists(inst.file))
            {
                continue; // Jump to next iteration
            }

            Console.WriteLine(inst.file);
        });
Run Code Online (Sandbox Code Playgroud)

然而,编译器声明没有什么可以跳出来(大概是因为它似乎把if块作为封闭块?).

反正有没有做上述事情?像parentblock.continue;等等的东西

谢谢

Chr*_*ain 8

使用return语句而不是continue.请记住,通过使用ForEach扩展方法,您正在为每个项执行一个函数,其主体在{和}之间指定.通过退出该函数,它将继续列表中的下一个值.


Joe*_*oey 5

ForEach在这种情况下,只是为列表中的每个项执行委托的方法.它不是循环控制结构,所以continue不能出现在那里.将其重写为正常foreach循环:

foreach (var inst in instructions) {
    if (!File.Exists(inst.file))
    {
        continue; // Jump to next iteration
    }

    Console.WriteLine(inst.file);
}
Run Code Online (Sandbox Code Playgroud)


Jam*_*mes 5

使用LINQ的Where子句从一开始就应用谓词

foreach(Instruction inst in instructions.Where(i => File.Exists(i.file))){
    Console.WriteLine(inst.file);
}
Run Code Online (Sandbox Code Playgroud)