List 는 배열처럼 값을 저장할 수 있는 클래스다.
List의 설명보다는 비슷하게 값을 저장하는 Array와 비교해가며 작성할 예정이다.
List<int> list1 = new List<int>() { 1, 2, 3, 4, 5 }; // 값으로 초기화
List<int> list2 = new List<int>(); // 빈 리스트
List<int> list3 = new List<int>(5); // 크기(capacity) 지정
초기화식은 배열과 비슷하다.
저장할 데이터 타입을 지정해, List<T>를 new로 생성한다.
그리고 제일 중요한, List를 사용할 때는 using System;과 같이
using System.Collections.Generic; 구문을 추가해줘야 한다.
둘 다 index라는 키에 값을 저장할 수 있지만, 큰 차이가 있다.
값의 갯수가 크기를 초과하면 자동으로 늘어나는데,
이때마다 새로운 메모리 공간을 할당하고 기존 데이터를 복사한다.
즉, 크기가 변경될 때마다 메모리 위치가 변경된다.
값의 갯수가 줄어도 크기는 자동으로 줄어들지 않는다.
이때는 TrimExcess()를 사용하면 크기를 값의 갯수만큼 줄일 수 있다.
array[i] = 1;로 값을 넣을 수 있다.list.Add(1);로 값을 넣을 수 있다.
특정 위치에 값을 삽입하려면 Insert(index, value)를 사용한다.
list.Insert(2, 999); // index 2 위치에 999 삽입
list.Remove(값)로 값을 삭제할 수 있다.
특정 값을 삭제하려면 Remove(value)를 사용한다.
단, 동일한 값이 여러 개 있을 경우 제일 앞의 값이 삭제된다.
bool isRemoved = list.Remove(999); // 삭제 성공 시 true 반환
특정 인덱스의 값을 삭제하려면 RemoveAt(index)를 사용한다.
list.RemoveAt(2); // index 2 위치 값 삭제
int[] arrayTest = { 1, 2, 3 };
Console.WriteLine($"함수전 : {string.Join(", ", arrayTest)}"); // 1, 2, 3
ArrayTest(arrayTest);
Console.WriteLine($"함수후 : {string.Join(", ", arrayTest)}"); // 1, 2, 3
static void ArrayTest(int[] array)
{
array = new int[array.Length];
}
List<int> listTest = new List<int>() { 1, 2, 3 };
Console.WriteLine($"함수전 : {listTest.Count}"); // 3
ListTest(listTest);
Console.WriteLine($"함수후 : {listTest.Count}"); // 0
static void ListTest(List<int> list)
{
list.Clear();
}
Array의 크기를 Length 프로퍼티로 확인할 수 있는 것처럼,
List는 Count와 Capacity 프로퍼티로 크기를 확인할 수 있다.
Count는 List안에 저장된 값의 개수
Capacity는 List의 크기
예를 들어,
List<int> listTest1 = new List<int>();
Console.WriteLine(listTest1.Capacity); // 출력: 0
List<int> listTest2 = new List<int>() { 1, 2, 3, 4, 5 };
Console.WriteLine(listTest2.Capacity); // 출력: 8
크기를 지정하지 않고 생성하면 Capacity는 0이지만,
초기값을 넣어 생성할 경우에는 List가 자동으로 여유 있는 크기(8)로 생성한다.
왜 8일까?
List의 크기는 값에 맞게 늘어나지 않고,
0 → 4 → 8 → 16 → 32 ... 이런식으로 두배씩 늘어난다.
int[] arrayTest = { 1, 2, 3 };
arrayTest.ToList(); // List 를 반환
List<int> listTest = new List<int>() { 1, 2, 3 };
listTest.ToArray(); // Array 를 반환
Array < > List 간의 타입 변화도 쉽게 가능하다.
Contains(value)를 사용한다.bool exists = list.Contains(3); // 존재하면 true, 없으면 false 반환IndexOf(value)를 사용한다. 값이 없으면 -1을 반환한다.int index = list.IndexOf(3);Array만 알고 있었을 때는 MSW의 table처럼 유동적으로 사용하지 못해서 답답했는데,
List는 크기에 신경안쓰고 사용한다는게 되게 편했다.
또한, 리스트 끝에 다른 리스트를 연결하는
AddRange(),
Capacity를Count에 맞춰 줄여주는TrimExcess()같은 내장 함수도 많아 더 유용하게 사용할 수 있을 것 같다.