C#에서 Foreach 루프 종료

Haider Ali 2023년10월12일
C#에서 Foreach 루프 종료

이 가이드는 C#에서 foreach 루프를 종료하는 방법을 알려줍니다. 이것은 또 다른 간단한 방법이며 복잡하지 않습니다.

이 가이드를 자세히 살펴보고 이 코드의 구현을 살펴보겠습니다.

C#에서 foreach 루프 종료

foreach 루프 또는 해당 문제에 대한 다른 루프를 종료하는 데 사용할 수 있는 두 가지 방법이 있습니다. foreach 루프에서 나가는 것은 다른 루프에서 나가는 것과 같습니다.

이 두 가지 방법 모두 매우 일반적이며 다른 많은 언어에서도 주로 사용되는 방법입니다. 예를 들어 C, C++, Java 등

break 방법이나 return 방법을 사용할 수 있습니다. 이 두 가지 방법 모두 foreach 루프를 종료하는 데 사용할 수 있습니다.

다음 코드를 살펴보십시오.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace For_Each_Loop {
  class Program {
    static void Main(string[] args) {
      int[] numbers_arr = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };  // Example Array

      foreach (int i in numbers_arr) {
        System.Console.Write("{0} ", i);
        Console.ReadKey();  // To Stay On Screen
        if (i == 3) {
          break;  // IF You want To break and end the function call
        }
      }

      foreach (int i in numbers_arr) {
        System.Console.Write("{0} ", i);
        Console.ReadKey();  // To Stay On Screen
        if (i == 2) {
          return;  // IF You want To break and end the function call
        }
      }
    }
  }
}

위의 코드에서 breakreturn을 모두 사용합니다. 필요에 따라 foreach 루프 내부에 break; 또는 return;을 작성하기만 하면 됩니다.

작가: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

관련 문장 - Csharp Loop