C# foreach 루프

WBOY
풀어 주다: 2024-09-03 15:11:22
원래의
731명이 탐색했습니다.

C#의 foreach 루프는 배열 또는 목록일 수 있는 항목 컬렉션을 반복하고, for 루프를 실행할 때 항목 컬렉션에 대한 코드 블록을 실행합니다. 컬렉션의 항목을 통과하고 마지막으로 하나씩 표시합니다. 하나.

구문:

foreach(dataType variableName in collection variable)
{
// codeblock
}
로그인 후 복사

위 구문에서 VariableName은 컬렉션의 현재 요소를 보유하고 컬렉션 변수는 반복되고 하나씩 표시될 목록 항목 컬렉션이 있는 IEnumerable 인터페이스를 구현하는 데이터 구조를 정의합니다. codeBlock에는 루프에서 실행될 로직이 포함되어 있습니다.

흐름도

foreach 루프 프로세스의 흐름을 살펴보겠습니다.

C# foreach 루프

C# foreach 루프는 어떻게 작동하나요?

foreach 루프의 작업 프로세스는 컬렉션의 요소를 반복하는 반면 foreach 루프를 사용하려면 명령문을 중괄호 {}로 묶어야 합니다. 루프 카운터 변수를 선언할 때 배열의 기본 유형과 동일한 유형을 선언할 수 있습니다.

예:

foreach(int items in arrayValues)
{
Console.WriteLine(items);
}
로그인 후 복사

키워드는 foreach 루프에서 항목을 반복하는 데 사용되며, 키워드는 매번 반복에서 항목을 선택하여 변수 요소에 저장합니다. 첫 번째 반복에서는 반복의 시작 항목이 요소에 저장되고 두 번째 반복에서는 다음 요소가 선택됩니다. foreach 루프는 배열이나 목록의 요소 수와 동일하게 실행됩니다.

for 루프와 foreach 루프의 차이점을 다음과 같이 살펴보겠습니다.

  • foreach 루프는 배열에 모든 요소가 나타날 때까지 명령문 블록을 실행하는 반면, for 루프는 주어진 조건이 false가 될 때까지 명령문 블록을 실행합니다.
  • foreach 루프에서는 배열을 정방향으로만 반복하지만 for 루프에서는 정방향과 역방향을 모두 반복합니다.
  • 변수 선언에서 foreach에는 5가지 유형이 있고 for 루프에는 3가지 유형 선언이 있습니다.0

foreach 루프에서는 goto, return, break 및 throw 문을 사용하여 루프를 중지하고 종료할 수 있는 코딩 조각도 볼 수 있습니다. 숫자가 12가 되면 코드가 실행을 종료하는 예를 살펴보겠습니다.

using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("foreach loop Sample!");
int[] oddArray = new int[] { 2,4,6,8,10,12,14,16,18,20 };
// Loop through array items
foreach (int num in oddArray)
{
Console.WriteLine(num);
// it don't read the number after 12
if (num == 12) break;
}
Console.ReadKey();
}
}
로그인 후 복사

forloop의 또 다른 예는 문자열에서 문자를 찾아야 하는 경우 foreach 루프를 사용하여 문자열에서 한 번에 한 문자씩 확인할 수 있으며, 문자열에서 문자 배열을 생성하고 한 문자만 읽을 수 있습니다. 동시에 문자 사이의 공백이 생략되도록 보장합니다.

// Reads one character at a time and it skips the process if space comes
string data = "C# Programming";
// it convert the string into an array of chars
char[] _array = data .ToCharArray();
// display one char at a time
foreach (char item in _array)
{
if (item.ToString() != " ")
Console.WriteLine(item);
}
로그인 후 복사

문자열에서 수집을 위해 foreach 루프를 사용하여 문자열에서 문자의 발생 횟수를 찾는 것을 보여줍니다.

string _string = "Latest C# Programming :Language";
char[] _charArray = _string.ToCharArray();
int _count = 0;
// Loop through chars and find all 'n' and count them
foreach (char item in charArray )
{
if (item  == 'a')
_count++;
}
Console.WriteLine($"Total n found {_count}");
로그인 후 복사

foreach 루프를 사용하는 이 예에서는 모든 문자열을 한 번에 하나씩 읽고 표시하는 문자열 배열을 만듭니다.

// Array of  name list in string
string[] nameList = new string[]
{ "Chand", "Leo", "Smith", "Allen", "Rick" };
// Loop through array and read all authors
foreach (string item in nameList )
{
Console.WriteLine(item );
}
로그인 후 복사

C# foreach 루프의 예

foreach 루프에 대한 프로그램 샘플을 살펴보겠습니다. 다음 프로그램은 foreach 루프를 사용하여 배열 요소를 통한 반복을 보여줍니다.

프로그램 #1

코드:

using System;
class Program_1
{
// Main Method
public static void Main(string[] args)
{
Console.WriteLine("Display Elements");
// creating an array
char[] _arrayList={'L','O','O','P','I','N','G'};
// it execute the loop till the last appearance of element in the array
foreach(char items in _arrayList)
{
Console.WriteLine(items);
}
}
}
로그인 후 복사

출력:

C# foreach 루프

프로그램 #2

코드:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Program_2
{
class Program_2
{
static void Main(string[] args)
{
string[] data = new string[5]; // declaring array
//Storing value in array element
data[0] = "Java";
data[1] = "DotNet";
data[2] = "PHP";
data[3] = "SQL SERVER";
data[4] = "ANDROID";
//retrieving value using foreach loop
foreach (string items in data)
{
Console.WriteLine("Welcome " + items);
}
//Console.ReadLine();
}
}
}
로그인 후 복사

출력:

C# foreach 루프

위의 foreach 배열 예시와 같이 목록 개체와 함께 루프를 사용하여 목록 개체의 요소에 액세스할 수 있습니다. 목록 요소를 반복하기 위해 foreach 루프를 사용하는 다음 예제를 살펴보겠습니다.

프로그램 #3

코드:

using System;
using System.Collections.Generic;
namespace Program_3
{
class Program_3
{
static void Main(string[] args)
{
List<string> nameList = new List<string>() { "Smith", "Steve", "Gates" };
foreach (string name in name list)
{
Console.WriteLine(name);
}
Console.WriteLine("Press Enter Key to Exit..");
}
}
}
로그인 후 복사

출력:

C# foreach 루프

프로그램 #4

코드:

using System;
class Program_4
{
// Main Method
public static void Main(String[] arg)
{
{
int[] codes = { 135, 142, 75, 106, 100 };
int newCodes = HighestCodes(codes);
Console.WriteLine("New Code is " + newCodes);
}
}
// method to find HighestCodes
public static int HighestCodes(int[] values)
{
int _num = values[0];
// for each loop
foreach (int item in values)
{
if (item > _num)
{
_num = item;
}
}
return _num;
}
}
로그인 후 복사

출력:

C# foreach 루프

결론

이 기사의 마지막 부분에서는 foreach 루프가 작동하는 방식과 배열 컬렉션의 값에 액세스하는 방법을 배웠으며 이해하기 쉽도록 구문, 순서도를 분석했습니다. 루핑에 대한 글을 이해하셨기를 바랍니다.

위 내용은 C# foreach 루프의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!