.net - 如何在 .NET 中克隆字典?

标签 .net data-structures

我知道我们应该使用字典而不是哈希表。但我找不到克隆字典的方法。即使将其转换为 ICollection(我这样做是为了获取 SyncRoot),我知道这也是不受欢迎的。

我现在正忙着改变它。我是否有正确的假设,即无法以通用方式实现任何类型的克隆,这就是字典不支持克隆的原因?

最佳答案

使用接受字典的构造函数。请参阅此示例

var dict = new Dictionary<string, string>();

dict.Add("SO", "StackOverflow");

var secondDict = new Dictionary<string, string>(dict);

dict = null;

Console.WriteLine(secondDict["SO"]);

只是为了好玩..您可以使用 LINQ!这是更通用的方法。

var secondDict = (from x in dict
                  select x).ToDictionary(x => x.Key, x => x.Value);

编辑

这应该适用于引用类型,我尝试了以下方法:

internal class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public User Parent { get; set; }
}

以及上面修改后的代码

var dict = new Dictionary<string, User>();

dict.Add("First", new User 
    { Id = 1, Name = "Filip Ekberg", Parent = null });

dict.Add("Second", new User 
    { Id = 2, Name = "Test test", Parent = dict["First"] });

var secondDict = (from x in dict
                  select x).ToDictionary(x => x.Key, x => x.Value);

dict.Clear();

dict = null;

Console.WriteLine(secondDict["First"].Name);

输出“Filip Ekberg”。

关于.net - 如何在 .NET 中克隆字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2279619/

相关文章:

sql-server - 游标有什么问题?

java - 将两个列表分别转换为新映射的键和值

c# - 工作环境的垃圾收集?

c# - 无法连接到 EntityFramework

matlab - 3 CUDA中的整数键查找

database - 部分堆排序以在 5GB 文件中找到 k 个最频繁出现的单词

algorithm - 二叉搜索树可能会因旋转而损坏吗?

c# - 如何在windows窗体中开发类似 "outlook 2007 send/receive progress"对话框的窗体?

c# - WPF 中真正的固定宽度字体

c# - .NET Remoting - 服务器如何更新客户端?