이미 생성된 목록에 항목을 삽입하려면 Insert() 메서드를 사용하십시오.
먼저 요소를 설정하십시오 -
List <int> list = new List<int>(); list.Add(989); list.Add(345); list.Add(654); list.Add(876); list.Add(234); list.Add(909);
이제 4번째 위치에 항목을 삽입해야 한다고 가정해 보겠습니다. 이를 위해 Insert() 메서드를 사용하십시오 -
// inserting element at 4th position list.Insert(3, 567);
전체 예를 살펴보겠습니다 -
예
using System;
using System.Collections.Generic;
namespace Demo {
public class Program {
public static void Main(string[] args) {
List < int > list = new List < int > ();
list.Add(989);
list.Add(345);
list.Add(654);
list.Add(876);
list.Add(234);
list.Add(909);
Console.WriteLine("Count: {0}", list.Count);
Console.Write("List: ");
foreach(int i in list) {
Console.Write(i + " ");
}
// inserting element at 4th position
list.Insert(3, 567);
Console.Write("\nList after inserting a new element: ");
foreach(int i in list) {
Console.Write(i + " ");
}
Console.WriteLine("\nCount: {0}", list.Count);
}
}
}