Deep Copy Dictionary in C#

In C#, implementing a deep copy of a HashMap can be achieved through the following steps:

  1. Create a new HashMap object.
  2. Iterate through each key-value pair in the original HashMap and make a deep copy of both the key and the value.
  3. Add the deep-copied key-value pairs to a new HashMap object.

Here is an example code to achieve a deep copy of a HashMap:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 创建一个原始的HashMap对象
        Dictionary<string, List<int>> originalMap = new Dictionary<string, List<int>>();
        originalMap.Add("key1", new List<int> { 1, 2, 3 });
        originalMap.Add("key2", new List<int> { 4, 5, 6 });

        // 创建一个新的HashMap对象用于深拷贝
        Dictionary<string, List<int>> deepCopyMap = new Dictionary<string, List<int>>();

        // 遍历原始HashMap,并进行深拷贝
        foreach (var kvp in originalMap)
        {
            string key = kvp.Key;
            List<int> value = new List<int>(kvp.Value); // 深拷贝

            deepCopyMap.Add(key, value);
        }

        // 输出原始HashMap和深拷贝后的HashMap
        Console.WriteLine("Original Map:");
        foreach (var kvp in originalMap)
        {
            Console.WriteLine($"{kvp.Key}: {string.Join(",", kvp.Value)}");
        }

        Console.WriteLine("\nDeep Copy Map:");
        foreach (var kvp in deepCopyMap)
        {
            Console.WriteLine($"{kvp.Key}: {string.Join(",", kvp.Value)}");
        }
    }
}

In the code above, we used List as the value, and performed a deep copy on the value. By creating a new List object and copying the elements from the original List to the new List, we achieved a deep copy. You can modify the code as needed to suit your requirements.

bannerAds