[英]How to deep copy a Dictionary containing a List in C#?
我需要制作一個Dictionary<string, List<int>>
的深層副本。 我試過了:
Dictionary<string, List<int>> tmpStudents =
new Dictionary<string, List<int>>(students);
但是操縱tmpStudents
的值仍在改變students
。 看來tmpStudents
中的列表仍在引用students
的列表,但是我不確定如何在不手動深度復制每個列表的情況下解決此問題。
您還需要復制列表; 您要做的只是復制字典,但是所有列表引用仍在它們之間共享。
使用LINQ相當容易:
var tmpStudents = students.ToDictionary(p => p.Key, p => p.Value.ToList());
嘗試這個:
var tmpStudents = students.ToDictionary(x => x.Key, x => x.Value.ToList());
因為您有一個List<int>
並且int
是一個值類型,所以應該可以使用。 否則,您必須分別為每個值創建一個深層副本。
使用BinaryFormatter
將您的Dictionary
序列化為MemoryStream
,然后將其反序列化回您的變量:
using (MemoryStream ms = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, oldStudants);
var newStudants = (Dictionary<String, List<int>>)formatter.Deserialize(ms);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.