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

Clone (Sao chép) Generic List trong C#

Dùng CopyTo copy sang array, hoặc constructor copy.

Cách 1: CopyTo array

List<string> myList = new List<string> { "Programming", "Web Dev", "Database" };
string[] arr = new string[myList.Count];
myList.CopyTo(arr);

Cách 2: Constructor List (Shallow Copy) - Khuyến nghị

List<string> cloned = new List<string>(myList);

Ví dụ

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        List<string> myList = new List<string> { "Programming", "Web Dev", "Database" };
        
        // Cách 1: CopyTo array
        string[] arr = new string[myList.Count];
        myList.CopyTo(arr);
        
        // Cách 2: List constructor (tạo List mới)
        List<string> cloned = new List<string>(myList);
        
        Console.WriteLine("Gốc:"); foreach (var v in myList) Console.WriteLine(v);
        Console.WriteLine("Clone:"); foreach (var v in cloned) Console.WriteLine(v);
    }
}

Kết quả

Gốc: Programming Web Dev Database
Clone: Programming Web Dev Database

Shallow vs Deep Copy: Cả hai cách đều shallow copy - copy reference cho reference type. Object tham chiếu vẫn shared. Deep copy cần serialize/deserialize hoặc manual clone.