Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy the content of a dictionary to an new dictionary in C#?

How can I copy a Dictionary<string, string> to another new Dictionary<string, string> so that they are not the same object?

like image 344
hansgiller Avatar asked May 11 '11 10:05

hansgiller


People also ask

How do I copy one dictionary to another?

The dict. copy() method returns a shallow copy of the dictionary. The dictionary can also be copied using the = operator, which points to the same object as the original. So if any change is made in the copied dictionary will also reflect in the original dictionary.

How do you initialize a new dictionary?

Dictionaries are also initialized using the curly braces {} , and the key-value pairs are declared using the key:value syntax. You can also initialize an empty dictionary by using the in-built dict function. Empty dictionaries can also be initialized by simply using empty curly braces.

Can dictionary store different data types?

One can only put one type of object into a dictionary. If one wants to put a variety of types of data into the same dictionary, e.g. for configuration information or other common data stores, the superclass of all possible held data types must be used to define the dictionary.


2 Answers

Assuming you mean you want them to be individual objects, and not references to the same object pass the source dictionary into the destination's constructor:

Dictionary<string, string> d = new Dictionary<string, string>(); Dictionary<string, string> d2 = new Dictionary<string, string>(d); 

"so that they are not the same object."

Ambiguity abound - if you do actually want them to be references to the same object:

Dictionary<string, string> d = new Dictionary<string, string>(); Dictionary<string, string> d2 = d; 

(Changing either d or d2 after the above will affect both)

like image 68
Jaymz Avatar answered Oct 08 '22 10:10

Jaymz


using System; using System.Collections.Generic;  class Program {     static void Main(string[] args)     {         Dictionary<string, string> first = new Dictionary<string, string>()         {             {"1", "One"},             {"2", "Two"},             {"3", "Three"},             {"4", "Four"},             {"5", "Five"},             {"6", "Six"},             {"7", "Seven"},             {"8", "Eight"},             {"9", "Nine"},             {"0", "Zero"}         };          Dictionary<string, string> second = new Dictionary<string, string>();         foreach (string key in first.Keys)         {             second.Add(key, first[key]);         }          first["1"] = "newone";         Console.WriteLine(second["1"]);     } } 
like image 37
Amal Hashim Avatar answered Oct 08 '22 08:10

Amal Hashim