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

Clone หรือ Copy List ใน C#

ภาพรวม

คัดลอก List ใน C# มีหลายวิธี: Shallow Copy (คัดลอก Reference) และ Deep Copy (คัดลอก Object ใหม่ทั้งหมด)

โค้ดตัวอย่าง: Shallow Copy


using System;
using System.Collections.Generic;
using System.Linq;

public class Demo {
    public static void Main() {
        List<string> original = new List<string> { "One", "Two", "Three", "Four" };

        Console.WriteLine("Original:");
        original.ForEach(Console.WriteLine);

        // วิธีที่ 1: Constructor (Shallow Copy)
        List<string> copy1 = new List<string>(original);

        // วิธีที่ 2: ToList() (Shallow Copy)
        List<string> copy2 = original.ToList();

        // วิธีที่ 3: CopyTo Array แล้ว ToList
        string[] arr = new string[original.Count];
        original.CopyTo(arr);
        List<string> copy3 = arr.ToList();

        // วิธีที่ 4: AddRange
        List<string> copy4 = new List<string>();
        copy4.AddRange(original);

        // ทดสอบ Independence
        copy1.Add("Five");
        Console.WriteLine($"\nOriginal Count: {original.Count}"); // 4
        Console.WriteLine($"Copy1 Count: {copy1.Count}"); // 5

        // สำหรับ Reference Type - Element ยัง Share Reference
        List<StringBuilder> refList = new List<StringBuilder> {
            new StringBuilder("A"),
            new StringBuilder("B")
        };
        var shallowCopy = new List<StringBuilder>(refList);
        shallowCopy[0].Append(" Modified");
        Console.WriteLine($"Original[0]: {refList[0]}"); // A Modified (Shared!)
        Console.WriteLine($"Copy[0]: {shallowCopy[0]}");   // A Modified
    }
}

Deep Copy สำหรับ Reference Types


using System;
using System.Collections.Generic;
using System.Text;

public class DeepCopyDemo {
    public static void Main() {
        List<Person> original = new List<Person> {
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Bob", Age = 25 }
        };

        // Manual Deep Copy
        List<Person> deepCopy = original.Select(p => new Person {
            Name = p.Name,
            Age = p.Age
        }).ToList();

        // ทดสอบ
        deepCopy[0].Age = 99;
        Console.WriteLine($"Original[0].Age: {original[0].Age}"); // 30 (ไม่เปลี่ยน)
        Console.WriteLine($"Copy[0].Age: {deepCopy[0].Age}");     // 99
    }
}

public class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}

Serialization-based Deep Copy (Generic)


using System.Text.Json;

public static class ListExtensions {
    public static List<T> DeepClone<T>(this List<T> source) {
        string json = JsonSerializer.Serialize(source);
        return JsonSerializer.Deserialize<List<T>>(json);
    }
}

// ใช้งาน
var deepCopy = original.DeepClone();

สรุปวิธี Copy

MethodTypePerformanceNote
new List<T>(original)ShallowFastStandard way
original.ToList()ShallowFastLINQ extension
original.GetRange(0, count)ShallowFastSubset copy
Manual Select + NewDeepMediumต้องเขียน mapping เอง
JSON Serialize/DeserializeDeepSlowGeneric, ต้อง Serializable
BinaryFormatter (Legacy)DeepSlowDeprecated, ไม่ปลอดภัย