views:

5822

answers:

6

I've got a generic dictionary Dictionary that I would like to essentially make a Clone() of ..any suggestions.

+4  A: 

(Note: although the cloning version is potentially useful, for a simple shallow copy the constructor I mention in the other post is a better option.)

How deep do you want the copy to be, and what version of .NET are you using? I suspect that a LINQ call to ToDictionary, specifying both the key and element selector, will be the easiest way to go if you're using .NET 3.5.

For instance, if you don't mind the value being a shallow clone:

var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
                                               entry => entry.Value);

If you've already constrained T to implement ICloneable:

var newDictionary = oldDictionary.ToDictionary(entry => entry.Key, 
                                               entry => (T) entry.Value.Clone());

(Those are untested, but should work.)

Jon

Jon Skeet
Thanks for the answer Jon. I'm actually using v2.0 of the framework.
mikeymo
+11  A: 

Okay, the .NET 2.0 answers:

If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary. (You can specify the comparer as the existing dictionary's comparer, too.)

If you do need to clone the values, you can use something like this:

public static Dictionary<TKey, TValue> CloneDictionaryCloningValues(Dictionary<TKey, TValue> original) where TValue : ICloneable
{
    Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count, original.Comparer);
    foreach (KeyValuePair<TKey, TValue> entry in original)
    {
        ret.Add(entry.Key, (TValue) entry.Value.Clone());
    }
    return ret;
}
Jon Skeet
The code above is wrong. No return statement and adding the entry to itself instead of to ret. Useful though but needs to be fixed.
Jonathan
@Jonathan: Oops, thanks - fixed.
Jon Skeet
+4  A: 

For .NET 2.0 you could implement a class which inherits from Dictionary and implements ICloneable.

public class CloneableDictionary<TKey, TValue> : Dictionary<TKey, TValue> where TValue : ICloneable
{
    public IDictionary<TKey, TValue> Clone()
    {
     CloneableDictionary<TKey, TValue> clone = new CloneableDictionary<TKey, TValue>();

     foreach (KeyValuePair<TKey, TValue> pair in this)
     {
      clone.Add(pair.Key, (TValue)pair.Value.Clone());
     }

     return clone;
    }
}

You can then clone the dictionary simply by calling the Clone method. Of course this implementation requires that the value type of the dictionary implements ICloneable, but otherwise a generic implementation isn't practical at all.

Sarcastic
+2  A: 

You could always use serialization. You could serialize the object then deserialize it. That will give you a deep copy of the Dictionary and all the items inside of it. Now you can create a deep copy of any object that is marked as [Serializable] without writing any special code.

Here are two methods that will use Binary Serialization. If you use these methods you simply call

object deepcopy = FromBinary(ToBinary(yourDictionary));

public Byte[] ToBinary()
{
  MemoryStream ms = null;
  Byte[] byteArray = null;
  try
  {
    BinaryFormatter serializer = new BinaryFormatter();
    ms = new MemoryStream();
    serializer.Serialize(ms, this);
    byteArray = ms.ToArray();
  }
  catch (Exception unexpected)
  {
    Trace.Fail(unexpected.Message);
    throw;
  }
  finally
  {
    if (ms != null)
      ms.Close();
  }
  return byteArray;
}

public object FromBinary(Byte[] buffer)
{
  MemoryStream ms = null;
  object deserializedObject = null;

  try
  {
    BinaryFormatter serializer = new BinaryFormatter();
    ms = new MemoryStream();
    ms.Write(buffer, 0, buffer.Length);
    ms.Position = 0;
    deserializedObject = serializer.Deserialize(ms);
  }
  finally
  {
    if (ms != null)
      ms.Close();
  }
  return deserializedObject;
}
Shaun Bowe
+1  A: 

This covers creating a cloneable Dictionary class (as well as the List class) and implementing them as members of a deeply cloneable hierarchy: Deep Cloning in VB.NET

+2  A: 

Binary Serialization method works fine but in my tests it showed to be 10x slower than a non-serialization implementation of clone. Tested it on Dictionary>

loty