Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Chèn phần tử vào List tại vị trí cho trước C#

Dùng Insert(index, item) - index 0-based.

List<int> list = new List<int>();
list.Add(989); list.Add(345); list.Add(654);
list.Add(876); list.Add(234); list.Add(909);

// Chèn 567 tại vị trí 4 (index 3)
list.Insert(3, 567);

Ví dụ hoàn chỉnh

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 + " ");
            
            list.Insert(3, 567);
            
            Console.Write("\nSau khi chèn: "); foreach (int i in list) Console.Write(i + " ");
            Console.WriteLine("\nCount: {0}", list.Count);
        }
    }
}

Lưu ý:

  • Index hợp lệ: 0 đến Count (chèn cuối = Add)
  • Index > Count -> ArgumentOutOfRangeException
  • Phần tử từ index trở đi dịch phải
  • O(n) do phải shift elements