你如何在 .NET 中克隆字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2279619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you clone a dictionary in .NET?
提问by uriDium
I know that we should rather be using dictionaries as opposed to hashtables. I cannot find a way to clone the dictionary though. Even if casting it to ICollection which I do to get the SyncRoot, which I know is also frowned upon.
我知道我们应该使用字典而不是哈希表。我找不到克隆字典的方法。即使将它转换为 ICollection 以获取 SyncRoot,我知道这也令人不悦。
I am busy changing that now. Am I under the correct assumption that there is no way to implement any sort of cloning in a generic way which is why clone is not supported for dictionary?
我现在正忙着改变它。我是否正确假设无法以通用方式实现任何类型的克隆,这就是为什么字典不支持克隆?
回答by Filip Ekberg
Use the Constructor that takes a Dictionary. See this example
使用带有字典的构造函数。看这个例子
var dict = new Dictionary<string, string>();
dict.Add("SO", "StackOverflow");
var secondDict = new Dictionary<string, string>(dict);
dict = null;
Console.WriteLine(secondDict["SO"]);
And just for fun.. You can use LINQ! Which is a bit more Generic approach.
只是为了好玩.. 你可以使用 LINQ!这是一种更通用的方法。
var secondDict = (from x in dict
select x).ToDictionary(x => x.Key, x => x.Value);
Edit
编辑
This should work well with Reference Types, I tried the following:
这应该适用于引用类型,我尝试了以下操作:
internal class User
{
public int Id { get; set; }
public string Name { get; set; }
public User Parent { get; set; }
}
And the modified code from above
以及上面修改后的代码
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);
Which outputs "Filip Ekberg".
输出“Filip Ekberg”。
回答by Bobby
This is a quick and dirty clone method I once wrote...the initial idea is from CodeProject, I think.
这是我曾经写过的一种快速而肮脏的克隆方法……我认为最初的想法来自 CodeProject。
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Public Shared Function Clone(Of T)(ByVal inputObj As T) As T
'creating a Memorystream which works like a temporary storeage '
Using memStrm As New MemoryStream()
'Binary Formatter for serializing the object into memory stream '
Dim binFormatter As New BinaryFormatter(Nothing, New StreamingContext(StreamingContextStates.Clone))
'talks for itself '
binFormatter.Serialize(memStrm, inputObj)
'setting the memorystream to the start of it '
memStrm.Seek(0, SeekOrigin.Begin)
'try to cast the serialized item into our Item '
Try
return DirectCast(binFormatter.Deserialize(memStrm), T)
Catch ex As Exception
Trace.TraceError(ex.Message)
return Nothing
End Try
End Using
End Function
Useage:
用途:
Dim clonedDict As Dictionary(Of String, String) = Clone(Of Dictionary(Of String, String))(yourOriginalDict)
回答by Amarnasan
Just in cause anyone needs the vb.net version
只是因为任何人都需要 vb.net 版本
Dim dictionaryCloned As Dictionary(Of String, String)
dictionaryCloned = (From x In originalDictionary Select x).ToDictionary(Function(p) p.Key, Function(p) p.Value)
回答by Marcello
For a primitive type dictionary
对于原始类型字典
Public Sub runIntDictionary()
Dim myIntegerDict As New Dictionary(Of Integer, Integer) From {{0, 0}, {1, 1}, {2, 2}}
Dim cloneIntegerDict As New Dictionary(Of Integer, Integer)
cloneIntegerDict = myIntegerDict.Select(Function(x) x.Key).ToList().ToDictionary(Of Integer, Integer)(Function(x) x, Function(y) myIntegerDict(y))
End Sub
For a dictionary of an Object that implements ICloneable
对于实现 ICloneable 的 Object 的字典
Public Sub runObjectDictionary()
Dim myDict As New Dictionary(Of Integer, number) From {{3, New number(3)}, {4, New number(4)}, {5, New number(5)}}
Dim cloneDict As New Dictionary(Of Integer, number)
cloneDict = myDict.Select(Function(x) x.Key).ToList().ToDictionary(Of Integer, number)(Function(x) x, Function(y) myDict(y).Clone)
End Sub
Public Class number
Implements ICloneable
Sub New()
End Sub
Sub New(ByVal newNumber As Integer)
nr = newnumber
End Sub
Public nr As Integer
Public Function Clone() As Object Implements ICloneable.Clone
Return New number With {.nr = nr}
End Function
Public Overrides Function ToString() As String
Return nr.ToString
End Function
End Class

