■컬렉션
(복수의 데이터를 다루기 위한 클래스의 집합)
List
- 배열처럼 복수의 데이터를 다룰 수 있고, 동적으로 요소 수를 변경할 수 있어 편리하다.
ex)
List<int> a = new List<int>();
a.Add(10);
// int형 수치를 저장할 경우 List<int> 이렇게 기술한다.
// a.Add(10); - 요소를 동적으로 하나 추가하고, 추가한 요소에 10을 설정합니다.
코딩
ex)
using System;
using System.Collections.Generic; /*List를 사용하는데 필요하다.*/
class ColorClass
{
static void Main(string[] args)
{
List<string> color = new List<string>(); /*List<strng> 배열처럼 액세스가능
color.Add(”blue”); /* int a[0] */
color.ADD(”red”); /* int a[1] */
Console.WriteLine(”color[0] = ” + color[0]); /* 0번 컬러가 blue
Console.WriteLine(”color[1] = ” + color[1]); /* 1번 컬러가 red
}
}
/* 출력결과
color[0] = blue
color[1] = red
*/
■컬렉션 초기화
-컬렉션의 초깃값은 Add()를 사용하지 않고 지정할 수 있다.
List<int> a = new List<int> {10, 20, 30}; —> a[0]=10, a[1]=20, a[2]=30 으로 초기화된다.
■요소삭제
컬렉션의 특정 요소를 삭제하려면 RemoveAt() 을 사용한다.
List<int> a = new List<int>() {10, 20, 30};
a.RemoveAt(1);
—> a[1]을 삭제한다. a[0]=10, a[1]=30 이 된다.
■열거형
(정수값에 특정 이름을 붙인 것을 열거형 이라고 한다.)
-열거형 선언은 enum(이념 이라고 읽음) 을 먼저 적는다.
ex)enum Animal { mouse, cat, bird, dog, koala, pig, lion };
-Animal 이 열거형명이 되고 {}중괄호 안의 내용이 열거 정수가 되며 ,(쉼표)로 구분한다.
mouse | cat | bird | dog | koala | pig | lion |
0 | 1 | 2 | 3 | 4 | 5 | 6 |
*여기서 임의의 수를 적용하게 되면 그 수로 부터 1씩 증가하게 된다.
enum Animal { mouse, cat, bird, dog=100, koala, pig=200, lion };
mouse | cat | bird | dog=100 (임의의정수값) | koala | pig=200 (임의의정수값) | lion |
0 | 1 | 2 | 100 | 101 | 200 | 201 |
- int형 이외의 형식으로 선언할시 :콜론을 이용해서 형을 지정한다.
enum Animal : byte { mouse, cat, bird, dog=100, koala, pig=200, lion };
: 콜론 byte정수형
mouse, cat, bird, dog=100, koala, pig=200, lion
mouse | cat | bird | dog | koala | pig | lion |
0 | 1 | 2 | 100 | 101 | 200 | 201 |
코딩ex)
using System;
class Enumsample
{
enum Animal {mouse, cat, bird, dog=100, koala, pig=200, lion};
static void Main()
{
Animal a;
a = Animal.dog; /*열거형명.열거정수*/
Console.WriteLine(Animal.cat);
/* 열거 정수 -- 식별자 참조를 위해 열겨형명.열거 정수 와 같이 적는다.*/
Console.WriteLine((int)Animal.dog);
/* int(정수형)을 앞에 붙여 형을 변환하면 정수 값을 참조할 수 있다.*/
Console.WriteLine((int)Animal.lion);
/* int(정수형)을 앞에 붙여 형을 변환하면 정수 값을 참조할 수 있다.*/
Console.WriteLine(a);
}
}
/*출력결과
cat
100
201
dog
*/
'프로그래머 > 코딩(C#)개념정리' 카테고리의 다른 글
C#_연산자_1 (4) | 2023.02.07 |
---|---|
C#_연산자 (1) | 2023.02.07 |
C#_배열 (2) | 2023.02.06 |
C#_문자, 문자열 (2) | 2023.02.06 |
C#_수치형(정수형, 실수형) (2) | 2023.02.06 |