How do you clone a dictionary in .NET?
Just in cause anyone needs the vb.net version
Dim dictionaryCloned As Dictionary(Of String, String)
dictionaryCloned = (From x In originalDictionary Select x).ToDictionary(Function(p) p.Key, Function(p) p.Value)
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.
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".
This is a quick and dirty clone method I once wrote...the initial idea is from CodeProject, I think.
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)