C#에서 Collection<T> 클래스가 제공하는 Insert 메서드를 사용하면 컬렉션의 지정된 인덱스 위치에 새로운 요소를 삽입할 수 있습니다. Insert 메서드는 첫 번째 매개변수로 삽입할 위치의 인덱스(0부터 시작)를, 두 번째 매개변수로 삽입할 값을 전달받습니다. 요소가 삽입되면 해당 위치 이후의 기존 요소들은 자동으로 한 칸씩 뒤로 밀려납니다.
예제
다음은 지정된 인덱스에 컬렉션 요소를 삽입하는 코드입니다.
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main(){
Collection<string> col = new Collection<string>();
col.Add("Laptop");
col.Add("Desktop");
col.Add("Notebook");
col.Add("Ultrabook");
col.Add("Tablet");
col.Add("Headphone");
col.Add("Speaker");
Console.WriteLine("Elements in Collection...");
foreach(string str in col){
Console.WriteLine(str);
}
Console.WriteLine("Element at index 3 = " + col[3]);
Console.WriteLine("Element at index 4 = " + col[4]);
col.Insert(5, "Alienware");
Console.WriteLine("Elements in Collection...UPDATED");
foreach(string str in col){
Console.WriteLine(str);
}
}
}출력
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Elements in Collection... Laptop Desktop Notebook Ultrabook Tablet Headphone Speaker Element at index 3 = Ultrabook Element at index 4 = Tablet Elements in Collection...UPDATED Laptop Desktop Notebook Ultrabook Tablet Alienware Headphone Speaker
실행 결과를 보면 col.Insert(5, "Alienware") 호출 후 인덱스 5 위치에 "Alienware"가 삽입되고, 기존에 있던 "Headphone"과 "Speaker"는 각각 한 칸씩 뒤로 이동한 것을 확인할 수 있습니다.
예제 2
이번에는 문자열 이름 목록에서 특정 위치에 요소를 삽입하는 또 다른 예제를 살펴보겠습니다.
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main(){
Collection<string> col = new Collection<string>();
col.Add("Andy");
col.Add("Kevin");
col.Add("John");
col.Add("Kevin");
col.Add("Mary");
col.Add("Katie");
col.Add("Barry");
col.Add("Nathan");
Console.WriteLine("Elements in Collection...");
foreach(string str in col){
Console.WriteLine(str);
}
col.Insert(3, "Jacob");
Console.WriteLine("Elements in Collection...UPDATED");
foreach(string str in col){
Console.WriteLine(str);
}
}
}출력
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Elements in Collection... Andy Kevin John Kevin Mary Katie Barry Nathan Elements in Collection...UPDATED Andy Kevin John Jacob Kevin Mary Katie Barry Nathan
이처럼 Insert 메서드를 활용하면 컬렉션의 원하는 위치에 손쉽게 새 요소를 추가할 수 있으며, 삽입된 위치 이후의 요소들은 인덱스가 자동으로 재조정됩니다.