Clone a Dictionary in C#
This post will discuss how to clone a Dictionary<TKey,TValue> in C#.
1. Using Dictionary<TKey,TValue>.ToDictionary() Method
To get a copy of a dictionary with keys associated with their corresponding values, you can use LINQ’s ToDictionary() method, as demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("White", "#FFFFFF"); dict.Add("Grey", "#808080"); dict.Add("Silver", "#C0C0C0"); dict.Add("Black", "#000000"); var dictCopy = dict.ToDictionary(entry => entry.Key, entry => entry.Value); Console.WriteLine(String.Join(", ", dictCopy)); } } |
Output:
[White, #FFFFFF], [Grey, #808080], [Silver, #C0C0C0], [Black, #000000]
The above version creates a shallow copy of dictionary values. If you need to create a to deep copy of Dictionary<TKey,TValue> values, you can have TValue implement ICloneable and invoke its Clone() method.
|
1 |
var dictCopy = dict.ToDictionary(entry => entry.Key, entry => (TValue) entry.Value.Clone()); |
2. Using Dictionary<TKey,TValue> Constructor
Alternatively, you can use the constructor of the Dictionary<TKey,TValue> class, which can take another instance of the same class and copy the object. The following example performs a shallow copy operation on dictionary values using its constructor.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("White", "#FFFFFF"); dict.Add("Grey", "#808080"); dict.Add("Silver", "#C0C0C0"); dict.Add("Black", "#000000"); var dictCopy = new Dictionary<string, string>(dict); Console.WriteLine(String.Join(", ", dictCopy)); } } |
Output:
[White, #FFFFFF], [Grey, #808080], [Silver, #C0C0C0], [Black, #000000]
That’s all about cloning a Dictionary<TKey,TValue> in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)