How to clone (deep copy) dictionary

Regarding this, which I stumbled onto tonight:

How would I copy one dictionary to another so that they are completely separate dictionaries? I think this is called a deep copy. Clone?

Hi @postwick

Please check this expression:

destinationDictionary = sourceDictionary.ToDictionary(Function(kvp) kvp.Key, Function(kvp) kvp.Value)

Best Regards.

1 Like

Hi,

Which type do you want to copy deeply?

If it’s Dictionary<string, List<string>> , the following will work.

dict2 = dict1.ToDictionary(Function(kv) kv.Key,Function(kv) kv.Value.Copy)

Regards,

1 Like

Speficially I’m copying transactionItem.SpecificContent so it’s “of dictionary, object”

I’m curious why it would be different for a different type of dictionary. It looks like the only difference is you added .Copy on the end of kv.Value

@postwick

As per @Yoichi’s expression (.Copy on the end of kv.Value), the modification is used when the values of the dictionary are mutable objects. By calling .Copy on each value, it will ensure that a new instance of the object is created, making a deep copy of the entire dictionary.

Also, please note that the .Copy method may not be available for all types of objects, and you may need to implement a custom cloning mechanism or use specific methods provided by the objects you are working with.

Best Regards.

1 Like

Hi,

In case of Dictionary<string, List<string>> ,
If we use dict2 = dict1.ToDictionary(Function(kv) kv.Key,Function(kv) kv.Value), it’s shallow copy.
For example, if we update value of dict2, value of dict1 will be updated, too.
As List<T> has Copy method as deep copy, we can use the following expression as deep copy.

dict2 = dict1.ToDictionary(Function(kv) kv.Key,Function(kv) kv.Value.Copy)

In case of Dictionary<string, object> , it’s no problem to use dict1.ToDictionary(Function(kv) kv.Key,Function(kv) kv.Value)

Regards,

1 Like

To make sure I understand this right, for simple datatypes like string, datetime, etc it won’t matter.

But for something like a list, datatable, or other such datatypes - while the dictionary clone is deep, the object value is still shallow?

Hi,

I think your understanding seems mostly correct.

Basically, it depends variable type: Value types or Reference types.
It’s unnecessary special care to copy Value types such as Int32, Double etc.
However, Reference Types such as List, array etc are needed special care (Copy method etc. if they have) to copy deeply. (Without it, it will be shallow copy)
Note: String type (and object type) is special type and it behaves like value type when copy even though it’s reference type.

Regards,

2 Likes

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.