본문 바로가기
C#/List

[C#] List 메서드 모음

by 스누ㅍl 2024. 7. 17.

최근 수정: 2024.09.09

List 메서드 내용 중 새로 알게되거나 사용했던 메서드들 기록하는 곳입니다.

 

주요 메서드

  • Count : 리스트의 길이를 반환한다.
List<int> lst = new List<int>();
lst.Add(1);
lst.Add(2);
lst.Add(3);

Console.WriteLine(lst.Count); // 3

 

  • Last() : 리스트의 마지막 값을 반환한다.
List<int> lst = new List<int>() { 1, 2, 3, 4, 5 };
Console.WriteLine(lst.Last()); // 5

 

  • Add([추가할 요소]) : 리스트 끝에 요소를 추가한다.
  • Append([추가할 요소]): 리스트 끝에 요소를 추가한 시퀀스를 반환한다. ※ 원본에 변경이 생기지 않음
List<int> lst = new List<int>() { 1, 2, 3 };
lst.Append(4);
lst.Add(5);

foreach (int i in lst) Console.Write(i + " "); // 1 2 3 5

var lst2 = lst.Append(4);
foreach (int i in lst2) Console.Write(i + " "); // 1 2 3 5 4

 

  • AddRange([배열]) : 한번에 다수의 요소를 추가한다.
int[] arr = { 4, 5, 6 };
List<int> lst = new List<int>() { 1, 2, 3 };
lst.AddRange(arr);

Console.WriteLine(string.Join(",", lst)); // 1,2,3,4,5,6

 

  • Remove([삭제할 요소]) : 매개변수로 받은 요소를 삭제한다.
List<int> lst = new List<int>() { 1, 2, 3 };
lst.Remove(2);

foreach (int i in lst) Console.Write(i + " "); // 1 3

 

  • RemoveAt([삭제할 인덱스]) : 매개변수로 받은 인덱스에 담긴 요소를 삭제한다. 삭제되면 뒤의 요소들이 한칸씩 앞으로 당겨진다.
List<int> lst = new List<int>() { 1, 2, 3 };
lst.RemoveAt(1);

foreach (int i in lst) Console.Write(i + " "); // 1 3

Console.WriteLine(lst[1]); // 3

 

  • RemoveRange([시작 인덱스], [개수]) : 시작 인덱스로 부터 몇개를 삭제할지를 매개 변수로 받는다. 만약 개수를 생략하면 시작인덱스 부터 끝까지 삭제된다.
List<int> lst = new List<int> { 1, 2, 3, 4, 5 };

lst.RemoveRange(1, 3);

Console.WriteLine(string.Join(",", lst)); // 1,5

 

  • GetRange([시작 인덱스], [개수]) : 시작 인덱스부터 몇개를 반환할지 매개변수로 받는다. list를 반환하며 원본엔 변화를 주지 않는다. 또한 RemoveRange와 달리 개수를 생략할 수 없다.
List<int> lst = new List<int> { 1, 2, 3, 4, 5 };

List<int> newList = lst.GetRange(1, 3);

Console.WriteLine(string.Join(",", newList)); // 2,3,4

 

  • Contains([확인할 요소]) : 매개변수와 동일한 요소가 있는지 확인해서 bool형으로 반환한다.
List<string> lst = new List<string>{ "abc", "def", "ghi" };

Console.WriteLine(lst.Contains("def")); // True
Console.WriteLine(lst.Contains("bcd")); // False