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

Chèn phần tử vào ArrayList tại chỉ số chỉ định C#

Ví dụ 1

Sử dụng Insert(index, value):

using System;
using System.Collections;

public class Demo {
    public static void Main() {
        ArrayList list = new ArrayList();
        list.Add("One");
        list.Add("Two");
        list.Add("Three");
        list.Add("Four");
        list.Add("Five");
        list.Add("Six");
        list.Add("Seven");
        list.Add("Eight");
        
        Console.WriteLine("Các phần tử ArrayList...");
        foreach(string str in list) {
            Console.WriteLine(str);
        }
        
        Console.WriteLine("ArrayList chỉ đọc? = " + list.IsReadOnly);
        Console.WriteLine("Có 'Six'? = " + list.Contains("Six"));
        
        list.Insert(4, "Twelve");
        
        Console.WriteLine("Các phần tử ArrayList...CẬP NHẬT");
        foreach(string str in list) {
            Console.WriteLine(str);
        }
    }
}

Kết quả

Các phần tử ArrayList...
One
Two
Three
Four
Five
Six
Seven
Eight
ArrayList chỉ đọc? = False
Có 'Six'? = True
Các phần tử ArrayList...CẬP NHẬT
One
Two
Three
Four
Twelve
Five
Six
Seven
Eight

Ví dụ 2

Chèn số nguyên:

using System;
using System.Collections;

public class Demo {
    public static void Main() {
        ArrayList arrList = new ArrayList();
        arrList.Add(100);
        arrList.Add(200);
        arrList.Add(300);
        arrList.Add(400);
        arrList.Add(500);
        
        Console.WriteLine("Hiển thị phần tử...");
        IEnumerator demoEnum = arrList.GetEnumerator();
        while (demoEnum.MoveNext()) {
            Object ob = demoEnum.Current;
            Console.WriteLine(ob);
        }
        
        arrList.Insert(4, 1000);
        
        Console.WriteLine("Hiển thị phần tử...CẬP NHẬT");
        demoEnum = arrList.GetEnumerator();
        while (demoEnum.MoveNext()) {
            Object ob = demoEnum.Current;
            Console.WriteLine(ob);
        }
    }
}

Kết quả

Hiển thị phần tử...
100
200
300
400
500
Hiển thị phần tử...CẬP NHẬT
100
200
300
400
1000
500