What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

mikeymo picture mikeymo · Sep 26, 2008 · Viewed 190.7k times · Source

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

Answer

Jon Skeet picture Jon Skeet · Sep 26, 2008

(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.)