簡體   English   中英

如何突破名單 <T> .ForEach()從C#中的if語句中循環

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

我想從if語句中跳過List<T>.ForEach()循環的迭代。

我有代碼:

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

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

但是,編譯器指出沒有什么可以跳出的(大概是因為它似乎將if塊作為封閉塊?)。

反正有做上面的嗎? 類似於parentblock.continue; 等等

謝謝

使用return語句而不是continue 請記住,通過使用ForEach擴展方法,您將為每個項目執行一個函數,其內容在{和}之間指定。 通過退出該功能,它將僅繼續列表中的下一個值。

在這種情況下, ForEach只是為列表中的每個項目執行委托的方法。 它不是循環控制結構,因此continue不會出現在該結構中。 將其重寫為普通的foreach循環:

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

    Console.WriteLine(inst.file);
}

使用LINQ的Where子句從一開始就應用謂詞

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

發送到ForEach函數的委托將對指令列表中的每個項目運行一次。 對於它跳過一項只是從委托函數返回。

    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