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

การคัดลอก ArrayList ทั้งหมดไปยังอาร์เรย์ 1 มิติใน C#

ภาพรวม

ArrayList.CopyTo(Array array) คัดลอกข้อมูลทั้งหมดไปยังอาร์เรย์ปลายทาง เริ่มที่ดัชนี 0 โดยอัตโนมัติ

ตัวอย่างที่ 1: คัดลอกสตริงไปอาร์เรย์ String[] ขนาด 10

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        ArrayList list = new ArrayList();
        list.Add("AB");
        list.Add("BC");
        list.Add("CD");
        list.Add("EF");
        list.Add("GH");
        list.Add("IJ");
        list.Add("KL");
        list.Add("MN");

        String[] strArr = new String[10];
        Console.WriteLine("ArrayList...");
        foreach (Object obj in list)
        {
            Console.WriteLine("{0}", obj);
        }

        list.CopyTo(strArr);
        Console.WriteLine("\nString Array after copying elements from ArrayList...");
        foreach (Object ob in strArr)
        {
            Console.WriteLine("{0}", ob);
        }
    }
}

ผลลัพธ์

ArrayList...
AB
BC
CD
EF
GH
IJ
KL
MN
String Array after copying elements from ArrayList...
AB
BC
CD
EF
GH
IJ
KL
MN

ตัวอย่างที่ 2: คัดลอกตัวเลขไปอาร์เรย์ int[] ขนาด 10

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        ArrayList list = new ArrayList();
        list.Add(100);
        list.Add(200);
        list.Add(300);
        list.Add(400);
        list.Add(500);
        list.Add(600);
        list.Add(700);
        list.Add(800);
        list.Add(900);
        list.Add(1000);

        int[] intArr = new int[10];
        Console.WriteLine("ArrayList...");
        foreach (Object obj in list)
        {
            Console.WriteLine("{0}", obj);
        }

        list.CopyTo(intArr);
        Console.WriteLine("\nInteger Array after copying elements from ArrayList...");
        foreach (Object ob in intArr)
        {
            Console.WriteLine("{0}", ob);
        }
    }
}

ผลลัพธ์

ArrayList...
100
200
300
400
500
600
700
800
900
1000
Integer Array after copying elements from ArrayList...
100
200
300
400
500
600
700
800
900
1000

สรุป

  • CopyTo(Array) เริ่มคัดลอกที่ดัชนี 0 เสมอ
  • อาร์เรย์ปลายทางต้องมีขนาด >= จำนวนข้อมูลใน ArrayList
  • ชนิดข้อมูลใน ArrayList ต้องเข้ากันได้กับชนิดอาร์เรย์ปลายทาง