如何创建Dictionary <int,List <int >>的副本而不影响原始(C#)?

How*_*ply 0 c# dictionary

我在C#中使用字典,我花了几个小时搞清楚为什么我的程序不起作用,原因是当我操作我制作的字典副本时,这些操作也会影响原始字典字典由于某种原因.

我把问题归结为以下示例:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<int, List<int>> D = new Dictionary<int, List<int>>();
        List<int> L1 = new List<int>(){ 1, 2, 3 };
        List<int> L2 = new List<int>() { 4, 5, 6 };
        D.Add(1,L1);
        D.Add(2,L2);
        Dictionary<int, List<int>> Dcopy = new Dictionary<int, List<int>>(D);
        Dcopy[1].Add(4);
    }
}
Run Code Online (Sandbox Code Playgroud)

在此代码中,当我向副本中的键1对应的列表中添加元素时,此元素也会出现在原始字典中.

当我在线搜索时,它似乎与"引用类型"有关,而推荐的修复似乎总是涉及类似于

Dictionary<int, List<int>> Dcopy = new Dictionary<int, List<int>>(D);
Run Code Online (Sandbox Code Playgroud)

我所做的包括在我的程序中,但由于某种原因,这不起作用.

有关为什么它在我的情况下不起作用的任何建议,以及关于该做什么的任何建议?

最好的祝福.

juh*_*arr 6

你正在做一个浅拷贝,而不是深拷贝.您基本上需要遍历字典并创建新列表

var Dcopy = new Dictionary<int, List<int>>();
foreach (var entry in D)
{
    Dcopy.Add(entry.Key, new List<int>(entry.Value));
} 
Run Code Online (Sandbox Code Playgroud)

或者您可以使用以下Linq而不是 foreach

var DCopy = D.ToDictionary(entry => entry.Key, entry => new List<int>(entry.Value));
Run Code Online (Sandbox Code Playgroud)

由于您的列表包含int哪个值类型,因此您不需要比列表更"克隆".如果列表包含引用类型,那么您还必须另外克隆它们,并且可能还有任何引用属性.

  • 请注意,如果列表中包含可变的内容(具有您可以设置的属性的类),您还需要复制列表中的每个项目(还要复制任何可变属性和属性属性等等)上...). (4认同)