C# Copy Dictionary

This C# program copies all the elements in a Dictionary into another.
Copy Dictionary. A Dictionary has a copy constructor. When you pass an existing Dictionary to its constructor, it is copied. This is an effective way to copy a Dictionary's data. When the original Dictionary is modified, the copy is not affected.ConstructorDictionary
Example. The simplest way of copying your Dictionary, using a custom loop over the keys, is prone to code duplication and errors. It doesn't make any sense to write the loop yourself. The code is present in the Dictionary class itself.

Main: Here we populate the Dictionary with three key-value pairs. We copy the Dictionary into the second Dictionary "copy".

Finally: The code adds a key to the first Dictionary, and displays both Dictionaries. The key added after the copy was made is not in the copy.

So: We use the copy constructor. And the example demonstrates how the internal structures are copied.

C# program that copies entire Dictionary using System; using System.Collections.Generic; class Program { static void Main() { // // Create and initialize Dictionary. // Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("cat", 1); dictionary.Add("dog", 3); dictionary.Add("iguana", 5); // // Copy the Dictionary to a second object. // Dictionary<string, int> copy = new Dictionary<string, int>(dictionary); // // Change the first Dictionary. It won't change the copy. // dictionary.Add("fish", 4); // // Display the first Dictionary. // Console.WriteLine("--- Dictionary 1 ---"); foreach (var pair in dictionary) { Console.WriteLine(pair); } // // Display the second Dictionary. // Console.WriteLine("--- Dictionary 2 ---"); foreach (var pair in copy) { Console.WriteLine(pair); } } } Output --- Dictionary 1 --- [cat, 1] [dog, 3] [iguana, 5] [fish, 4] --- Dictionary 2 --- [cat, 1] [dog, 3] [iguana, 5]
Internals. You can manually copy all elements in your Dictionary. Internally, the Dictionary constructor that accepts IDictionary is implemented with this loop. My research established that the foreach loop is fast and eliminates lookups.

Also: You could easily adapt the loop to copy to a Hashtable or List of KeyValuePair structs.

Implementation of Dictionary copy constructor: C# foreach (KeyValuePair<TKey, TValue> pair in dictionary) { this.Add(pair.Key, pair.Value); }
Summary. We copied an entire Dictionary to a new Dictionary. The Dictionary class does not define a Copy or CopyTo method. For this reason, using the copy constructor is the easiest and clearest way.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls