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

Chèn item vào ArrayList trong C#

ArrayList (non-generic) dùng Insert(index, item).

ArrayList arr = new ArrayList();
arr.Add(45); arr.Add(78); arr.Add(33);

// Chèn 90 tại index 1 (vị trí 2)
arr.Insert(1, 90);

Ví dụ

using System;
using System.Collections;

namespace Demo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            ArrayList arr = new ArrayList();
            arr.Add(45); arr.Add(78); arr.Add(33);
            
            Console.WriteLine("Count: {0}", arr.Count);
            Console.Write("ArrayList: "); foreach (int i in arr) Console.Write(i + " ");
            
            arr.Insert(1, 90);
            
            Console.Write("\nSau chèn: "); foreach (int i in arr) Console.Write(i + " ");
            Console.WriteLine("\nCount: {0}", arr.Count);
        }
    }
}

Kết quả

Count: 3
ArrayList: 45 78 33
Sau chèn: 45 90 78 33
Count: 4

Lưu ý:

  • ArrayList cũ, non-generic, boxing/unboxing overhead
  • Khuyến nghị dùng List<T> - type-safe, performance tốt hơn
  • List<int> list = new(); list.Insert(1, 90);