Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การแทรกสมาชิกเข้า ArrayList ที่ดัชนีที่ระบุใน C#

ภาพรวม

เมธอด ArrayList.Insert(int index, object value) แทรกสมาชิกที่ดัชนีที่กำหนด (0-based) ขยับสมาชิกเดิมไปท้าย

ตัวอย่างที่ 1: แทรก "Twelve" ที่ดัชนี 4

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("ArrayList elements...");
        foreach (string str in list)
        {
            Console.WriteLine(str);
        }

        Console.WriteLine("ArrayList is read-only? = " + list.IsReadOnly);
        Console.WriteLine("Does the element Six in the ArrayList? = " + list.Contains("Six"));

        list.Insert(4, "Twelve");

        Console.WriteLine("ArrayList elements...UPDATED");
        foreach (string str in list)
        {
            Console.WriteLine(str);
        }
    }
}

ผลลัพธ์

ArrayList elements...
One
Two
Three
Four
Five
Six
Seven
Eight
ArrayList is read-only? = False
Does the element Six in the ArrayList? = True
ArrayList elements...UPDATED
One
Two
Three
Four
Twelve
Five
Six
Seven
Eight

ตัวอย่างที่ 2: แทรกจำนวนเต็ม 1000 ที่ดัชนี 4

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("Display elements...");
        IEnumerator demoEnum = arrList.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Object ob = demoEnum.Current;
            Console.WriteLine(ob);
        }

        arrList.Insert(4, 1000);

        Console.WriteLine("Display elements...UPDATED");
        demoEnum = arrList.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Object ob = demoEnum.Current;
            Console.WriteLine(ob);
        }
    }
}

ผลลัพธ์

Display elements...
100
200
300
400
500
Display elements...UPDATED
100
200
300
400
1000
500

สรุป

  • Insert(index, value) ดัชนีต้องอยู่ในช่วง 0 ถึง Count (รวม Count คือเพิ่มท้าย)
  • ArrayList เป็น non-generic ควรใช้ List<T> แทน (List<T>.Insert ทำงานเหมือนกัน)
  • การแทรกที่กลางต้องขยับข้อมูล O(n)