Để chèn một mục trong Danh sách đã được tạo, hãy sử dụng phương thức Chèn ().
Đầu tiên, thiết lập các phần tử -
List <int> list = new List<int>(); list.Add(989); list.Add(345); list.Add(654); list.Add(876); list.Add(234); list.Add(909);
Bây giờ, giả sử bạn cần chèn một mục ở vị trí thứ 4. Để làm điều đó, hãy sử dụng phương thức Insert () -
// inserting element at 4th position list.Insert(3, 567);
Hãy để chúng tôi xem ví dụ hoàn chỉnh -
Ví dụ
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);
}
}
}