如何在 C# 中深度复制包含列表的字典?

Mar*_*aru 2 c#

我需要制作一个Dictionary<string, List<int>>. 我试过:

Dictionary<string, List<int>> tmpStudents =
   new Dictionary<string, List<int>>(students);
Run Code Online (Sandbox Code Playgroud)

但操纵 中的值tmpStudents仍在改变 中的值students。中的列表似乎tmpStudents仍在引用中的列表students,但我不确定如何在不手动深度复制每个列表的情况下解决此问题。

cdh*_*wie 5

您还需要深度复制列表;您所做的只是复制字典,但所有列表引用仍然在它们之间共享。

使用 LINQ 这很容易:

var tmpStudents = students.ToDictionary(p => p.Key, p => p.Value.ToList());
Run Code Online (Sandbox Code Playgroud)