본문 바로가기
C#

[C#] List Insert, List 앞에 더하기

by Minius 2022. 1. 4.
반응형

프로그래밍을 하다 보면 가끔 순서를 맞춰줘야 할 때가 있어서 리스트의 제일 앞에 값을 더해야 할 때가 있다.

이럴 때 나는 새로운 List를 만들어서 해결하곤 했다.

var list = new List<string>() {"b", "c", "d"};
var newList = new List<string>();

newList.Add("a");
newList.AddRange(list);

return newList;

 

가끔이지만, 매번 하면서도 이렇게 비효율적일 수 있나... 싶으면서도 찾지 못해 그대로 사용하고 있었다.

하지만 오늘 회사에서 코드 리뷰를 할 때 Insert 메소드를 배웠다.

 

var list = new List<string>() {"b", "c", "d"};

list.Add(0, "a");

return list;

0번째에 "a" 넣기...

 

다른건 다 알았었는데 왜 Insert는 몰랐을까

InsertRange도 AddRange와 같이 있다.

List에 대해 다시 한번 보게 되는 시간이 되었다.

 

List 메소드 보기

https://docs.microsoft.com/ko-kr/dotnet/api/system.collections.generic.list-1.add?view=net-6.0 

 

List<T>.Add(T) 메서드 (System.Collections.Generic)

개체를 List<T>의 끝 부분에 추가합니다.Adds an object to the end of the List<T>.

docs.microsoft.com

 

댓글