Home
Map
Copy DictionaryCopy all the elements in a Dictionary collection into another.
C#
This page was last reviewed on Mar 24, 2023.
Copy Dictionary. The C# 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.
Shows a dictionary
Notes, original. When the original Dictionary is modified, the copy is not affected. Once copied, a Dictionary has separate memory locations to the original.
Constructor
Dictionary
First example. We can use a custom loop over the keys, but this is prone to code duplication and errors. It makes no sense to write the loop yourself.
Part 1 We copy the Dictionary into the second Dictionary "copy" by using the copy constructor.
Part 2 The code adds a key to the first Dictionary. And we see that the key added after the copy was made is not in the copy.
Part 3 We print the contents of both collections. The example demonstrates how the internal structures are copied.
Console
Shows a dictionary
using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("cat", 1); dictionary.Add("dog", 3); dictionary.Add("iguana", 5); // Part A: copy the Dictionary to a second object. Dictionary<string, int> copy = new Dictionary<string, int>(dictionary); // Part B: change the first Dictionary. dictionary.Add("fish", 4); // Part C: display the 2 Dictionaries. Console.WriteLine("--- Dictionary 1 ---"); foreach (var pair in dictionary) { Console.WriteLine(pair); } Console.WriteLine("--- Dictionary 2 ---"); foreach (var pair in copy) { Console.WriteLine(pair); } } }
--- Dictionary 1 --- [cat, 1] [dog, 3] [iguana, 5] [fish, 4] --- Dictionary 2 --- [cat, 1] [dog, 3] [iguana, 5]
Internals. The Dictionary constructor that accepts IDictionary is implemented with this loop. My research established that the foreach-loop is fast and eliminates lookups.
Foreach
IDictionary
Also We could easily adapt the loop to copy to a Hashtable or List of KeyValuePair structs.
KeyValuePair
foreach (KeyValuePair<TKey, TValue> pair in dictionary) { this.Add(pair.Key, pair.Value); }
A summary. In C# we copied an entire Dictionary to a new Dictionary. As Dictionary does not define a Copy or CopyTo method, the copy constructor is the easiest way.
C#VB.NETPythonGolangJavaSwiftRust
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 24, 2023 (edit).
Home
Changes
© 2007-2023 Sam Allen.