简体   繁体   English

如何突破名单 <T> .ForEach()从C#中的if语句中循环

[英]How to break out of a List<T>.ForEach() loop from within an if statement in C#

I would like to skip an iteration of a List<T>.ForEach() loop from within an if statement. 我想从if语句中跳过List<T>.ForEach()循环的迭代。

I have the code: 我有代码:

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

            Console.WriteLine(inst.file);
        });

However the compiler states there is nothing to jump out from (presumably as it seems to take the if block as the enclosing block?). 但是,编译器指出没有什么可以跳出的(大概是因为它似乎将if块作为封闭块?)。

Is there anyway to do the above? 反正有做上面的吗? Something like parentblock.continue; 类似于parentblock.continue; etc. 等等

Thanks 谢谢

Use a return statement instead of continue . 使用return语句而不是continue Remember that by using the ForEach extension method, you are executing a function for each item, the body of which is specified between { and }. 请记住,通过使用ForEach扩展方法,您将为每个项目执行一个函数,其内容在{和}之间指定。 By exiting the function it will just continue with the next value from the list. 通过退出该功能,它将仅继续列表中的下一个值。

ForEach in this case is just a method executing a delegate for every item in the list. 在这种情况下, ForEach只是为列表中的每个项目执行委托的方法。 It is not a looping control structure so continue cannot appear there. 它不是循环控制结构,因此continue不会出现在该结构中。 Rewrite it as a normal foreach loop: 将其重写为普通的foreach循环:

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

    Console.WriteLine(inst.file);
}

Use LINQ's Where clause to apply the predicate from the onset 使用LINQ的Where子句从一开始就应用谓词

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

The delegate that is sent to the ForEach function will run once per item in the instructions list. 发送到ForEach函数的委托将对指令列表中的每个项目运行一次。 For it to skip one item just return from the delegate function. 对于它跳过一项只是从委托函数返回。

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

        Console.WriteLine(inst.file);
    });

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

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