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

การคัดลอกข้อมูล Collection ไปยังอาร์เรย์ใน C#

ภาพรวม

Collection<T>.CopyTo(T[] array, int index) คัดลอกข้อมูลทั้งหมดไปยังอาร์เรย์ปลายทาง เริ่มที่ดัชนีที่ระบุ

ตัวอย่างที่ 1: คัดลอก 8 สมาชิกไปอาร์เรย์ขนาด 10 เริ่มดัชนี 2

using System;
using System.Collections.ObjectModel;

public class Demo
{
    public static void Main()
    {
        Collection<string> col = new Collection<string>();
        col.Add("One");
        col.Add("Two");
        col.Add("Three");
        col.Add("Four");
        col.Add("Five");
        col.Add("Six");
        col.Add("Seven");
        col.Add("Eight");

        Console.WriteLine("Collection....");
        foreach (string str in col)
        {
            Console.WriteLine(str);
        }

        string[] strArr = new string[10];
        col.CopyTo(strArr, 2);

        Console.WriteLine("\nArray...");
        foreach (string str in strArr)
        {
            Console.WriteLine(str);
        }
    }
}

ผลลัพธ์

Collection....
One
Two
Three
Four
Five
Six
Seven
Eight
Array...
One
Two
Three
Four
Five
Six
Seven
Eight

ตัวอย่างที่ 2: คัดลอก 5 สมาชิกไปอาร์เรย์ขนาด 10 เริ่มดัชนี 3

using System;
using System.Collections.ObjectModel;

public class Demo
{
    public static void Main()
    {
        Collection<string> col = new Collection<string>();
        col.Add("One");
        col.Add("Two");
        col.Add("Three");
        col.Add("Four");
        col.Add("Five");

        Console.WriteLine("Collection....");
        foreach (string str in col)
        {
            Console.WriteLine(str);
        }

        string[] strArr = new string[10];
        col.CopyTo(strArr, 3);

        Console.WriteLine("\nArray...");
        foreach (string str in strArr)
        {
            Console.WriteLine(str);
        }
    }
}

ผลลัพธ์

Collection....
One
Two
Three
Four
Five
Array...
One
Two
Three
Four
Five

สรุป

  • Collection<T> เป็นคลาสฐานสำหรับคอลเลกชันแบบเจนเนริก
  • CopyTo() ต้องการอาร์เรย์ปลายทางขนาดพอ และดัชนีเริ่มต้น
  • ช่องว่างในอาร์เรย์จะเป็นค่า default (null สำหรับ reference type)