C#에는 foreach라는 반복문을 제공합니다. 이를 써보고 설명 하려고 합니다.
자바를 약간 다뤄본적이 있고 이와 유사한 형태가 있습니다.
int[] arr = {1, 2, 3, 4, 5};
for(int num : arr){ } 이와 같은 형태가 있으며 arr에 있는 값을 하나씩 돌며 num에 집어넣게 됩니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class Pair
{
public int First { get; set; }
public int Second { get; set; }
public Pair(int f, int s)
{
First = f;
Second = s;
}
}
class Program
{
static void Main(string[] args)
{
int[] intArr = { 1, 2, 3, 4, 5 };
string[] strArr = { "1", "2", "3", "4", "5" };
float[] floatArr = { 0.1f, 0.2f, 0.3f, 0.4f, 0.5f };
//첫번째 int배열 테스트
foreach (int num in intArr)
Console.WriteLine(num);
//1, 2, 3, 4, 5
Console.WriteLine("");
//두번째 string배열 테스트
foreach (string str in strArr)
Console.WriteLine(str);
//1, 2, 3, 4, 5
Console.WriteLine("");
//세번째 float배열 테스트
foreach (float f in floatArr)
Console.WriteLine(f);
//0.1, 0.2, 0.3, 0.4, 0.5
Console.WriteLine("");
//네번째 int 리스트 테스트
List<int> intList = new List<int> { 5, 6, 7, 8 };
foreach (int num in intList)
Console.WriteLine(num);
//5, 6, 7, 8
Console.WriteLine("");
List<Pair> pairList = new List<Pair> { new Pair(1, 2), new Pair(3, 4), new Pair(5, 6) };
foreach (Pair pair in pairList)
//첫번째 : 1, 두번째 : 2
//첫번째 : 3, 두번째 : 4
//첫번째 : 5, 두번째 : 6
//첫번째 : 7, 두번째 : 8
}
}
}
|
직접 써본 C#의 코드 입니다.
출력의 결과를 보면 int, string 등의 배열과 int List가 잘 작동되는 것을 알 수 있습니다.
타입을 직접 만든 클래스로 받는 List의 경우에도 각각 한번씩 돌며 출력이 제대로 됨을 알 수 있습니다.
List가 되는것을 보면 Collection의 List와 같은 반복자를 사용하고 선형적으로 이루어진 자료형의 경우
foreach문이 동작할 것으로 예상됩니다.
Excel 파일 Json으로 변환 프로젝트 (0) | 2020.04.23 |
---|---|
Excel 파일 Json으로 바꿔주는 프로그램 Ver 2.0 (0) | 2020.04.23 |
Excel파일을 json파일로 변환하는 프로그램 ver 1.0. (0) | 2020.04.22 |
C# List Sort예제. (0) | 2020.04.19 |
C# 생성자를 여러개 정의할 경우. (0) | 2020.04.16 |