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

โปรแกรม C# สร้าง List จากอาร์เรย์


ภาพรวม

สามารถสร้าง List<T> จากอาร์เรย์ได้โดยตรงผ่าน Constructor ที่รับ IEnumerable<T>

รูปแบบการใช้งาน

int[] arr = { 15, 25, 40, 58, 70 };
List myList = new List(arr); // คัดลอกข้อมูลจากอาร์เรย์

ตัวอย่างโค้ดเต็ม

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        int[] val = new int[5];
        val[0] = 15; val[1] = 25; val[2] = 40; val[3] = 58; val[4] = 70;
        List myList = new List(val);
        Console.WriteLine("Elements...");
        foreach (int res in myList) Console.WriteLine(res);
        Console.WriteLine("Number of elements: " + myList.Count);
    }
}

ผลลัพธ์

Elements...
15
25
40
58
70
Number of elements: 5

วิธีอื่นๆ

  • var list = arr.ToList(); - ใช้ LINQ (ต้อง using System.Linq;)
  • List list = new List(); list.AddRange(arr); - เพิ่มทีหลัง
  • ทั้งหมดเป็น shallow copy - ออบเจ็กต์ในลิสต์อ้างอิงตัวเดียวกับในอาร์เรย์ (สำคัญสำหรับ reference types)