SoFunction
Updated on 2025-03-07

Implementation method of multi-layer nesting of List and List in C# without changing the original value (deep copy)

Overview:The above content introduces in detail the implementation of multi-layer nested copying methods in C# that do not change the original List value, including steps and examples for using AutoMapper, and object serialization. These methods provide a flexible and efficient way to choose the most suitable deep replication method according to project requirements.

1. Multi-layer nested copy using AutoMapper

AutoMapper is an object mapping tool that allows easy mapping between objects. Here are the steps and examples for implementing multi-layer nested replication using AutoMapper:

First, you need to install the AutoMapper package in your project. You can install it by running the following command through the NuGet Package Manager console:

Install-Package AutoMapper

Then you can use the following code for deep copying:

using AutoMapper;
using System;
using ;
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
class Student
{
    public string StudentId { get; set; }
    public Person Info { get; set; }
}
class Program
{
    static void Main()
    {
        // Create original list, multi-layer nesting        List<Student> originalList = new List<Student>
        {
            new Student { StudentId = "001", Info = new Person { Name = "Alice", Age = 25 } },
            new Student { StudentId = "002", Info = new Person { Name = "Bob", Age = 30 } }
        };
        // Use AutoMapper to achieve deep replication        List<Student> copiedList = DeepCopyWithAutoMapper(originalList);
        // Modify the copied value        copiedList[0]. = "Charlie";
        // Print the original value and verify whether the value of the original List has changed        ("The value of the original List:");
        PrintList(originalList);
        // Print the copied value        ("\nThe value of List after copying:");
        PrintList(copiedList);
    }
    static List<Student> DeepCopyWithAutoMapper(List<Student> originalList)
    {
        // Initialize AutoMapper configuration        var config = new MapperConfiguration(cfg =>
        {
            // Map configuration for each layer of nested types            <Student, Student>();
            <Person, Person>();
        });
        // Create a mapper        IMapper mapper = ();
        // Use mapper for deep copy        List<Student> newList = <List<Student>>(originalList);
        return newList;
    }
    // How to print List    static void PrintList(List<Student> list)
    {
        foreach (var student in list)
        {
            ($"StudentId: {}, Name: {}, Age: {}");
        }
    }
}

In this example, the AutoMapper configuration is first initialized, and then the mapper is created, and deep replication is used.

2. Use multi-layer nested copy

() is a powerful library for processing JSON data, and can also be used to implement deep replication. Here are the steps and examples for implementing multi-layer nested replication using:

First, you need to install the package in the project. You can install it by running the following command through the NuGet Package Manager console:

Install-Package 

Then you can use the following code for deep copying:

using ;
using System;
using ;
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
class Student
{
    public string StudentId { get; set; }
    public Person Info { get; set; }
}
class Program
{
    static void Main()
    {
        // Create original list, multi-layer nesting        List<Student> originalList = new List<Student>
        {
            new Student { StudentId = "001", Info = new Person { Name = "Alice", Age = 25 } },
            new Student { StudentId = "002", Info = new Person { Name = "Bob", Age = 30 } }
        };
        // Use to achieve deep replication        List<Student> copiedList = DeepCopyWithJson(originalList);
        // Modify the copied value        copiedList[0]. = "Charlie";
        // Print the original value and verify whether the value of the original List has changed        ("The value of the original List:");
        PrintList(originalList);
        // Print the copied value        ("\nThe value of List after copying:");
        PrintList(copiedList);
    }
    static List<Student> DeepCopyWithJson(List<Student> originalList)
    {
        // Use JsonConvert for deep copying        string json = (originalList);
        List<Student> newList = <List<Student>>(json);
        return newList;
    }
    // How to print List    static void PrintList(List<Student> list)
    {
        foreach
 (var student in list)
        {
            ($"StudentId: {}, Name: {}, Age: {}");
        }
    }
}

In this example, using JsonConvert to convert the original List to a JSON string, and then deserialize it from the JSON string to obtain a new List, realizing deep copying.

3. Deep copying using object serialization and deserialization

Another common method is to use C#'s object serialization and deserialization functions to serialize objects into byte streams, and then deserialize them into new objects. Here are the steps and examples for implementing multi-layer nested replication using serialization and deserialization:

using System;
using ;
using ;
using ;
using ;
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
class Student
{
    public string StudentId { get; set; }
    public Person Info { get; set; }
}
class Program
{
    static void Main()
    {
        // Create original list, multi-layer nesting        List<Student> originalList = new List<Student>
        {
            new Student { StudentId = "001", Info = new Person { Name = "Alice", Age = 25 } },
            new Student { StudentId = "002", Info = new Person { Name = "Bob", Age = 30 } }
        };
        // Use serialization and deserialization to achieve deep replication        List<Student> copiedList = DeepCopyWithSerialization(originalList);
        // Modify the copied value        copiedList[0]. = "Charlie";
        // Print the original value and verify whether the value of the original List has changed        ("The value of the original List:");
        PrintList(originalList);
        // Print the copied value        ("\nThe value of List after copying:");
        PrintList(copiedList);
    }
    static List<Student> DeepCopyWithSerialization(List<Student> originalList)
    {
        IFormatter formatter = new BinaryFormatter();
        using (MemoryStream stream = new MemoryStream())
        {
            (stream, originalList);
            (0, );
            return (List<Student>)(stream);
        }
    }
    // How to print List    static void PrintList(List<Student> list)
    {
        foreach (var student in list)
        {
            ($"StudentId: {}, Name: {}, Age: {}");
        }
    }
}

In this example, using BinaryFormatter to serialize the original List into a byte stream, and then deserialize to obtain a new List, realizing deep copying.

This is the article about the implementation method of List and List in C#. This is all about this. For more related C#. List multi-layer nesting content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!