uriDium
uriDium

Reputation: 13420

How do you clone a dictionary in .NET?

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.

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?

Upvotes: 41

Views: 45090

Answers (7)

Ukkie
Ukkie

Reputation: 25

For Vb.net I discovered a more simple solution:

dim seconddic as Dictionary(of string,string) = new Dictionary(of string,string)(originaldic)

Upvotes: 2

Dmitry Shashurov
Dmitry Shashurov

Reputation: 1714

Simplest way:

Dictionary<string, int> oldDictionary = new Dictionary<string, int>();

Dictionary<string, int> newDictionary = new Dictionary<string, int>(oldDictionary);

Upvotes: 0

TachikomaWebI
TachikomaWebI

Reputation: 21

For simple Dictionary<String, Object>

public static Dictionary<string, object> DictionaryClone(Dictionary<string, object> _Datas)
{
    Dictionary<string, object> output = new Dictionary<string, object>();

    if (_Datas != null)
    {
        foreach (var item in _Datas)
            output.Add(item.Key, item.Value);
    }

    return output;
}

Upvotes: 0

Marcello
Marcello

Reputation: 448

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

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

Upvotes: 0

Amarnasan
Amarnasan

Reputation: 15529

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)

Upvotes: 2

Filip Ekberg
Filip Ekberg

Reputation: 36287

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".

Upvotes: 59

Bobby
Bobby

Reputation: 11576

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)

Upvotes: 2

Related Questions