Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C# - COPY FROM DICTIONARY


It is quite simple to make a copy of the Dictionary and assign it to other variable.


Example :



using System.Collections.Generic;
    
public class MyApplication
{
    public static void Main(string[] args)
    {
        Dictionary<object, string> x = new Dictionary<object, string>() 
        {
	        { 5, "Is a Number" }, 
	        { "John", "Is a Name" }, 
	        { "C#", "Is a Language"}
        };
        
        Dictionary<object, string> y = new Dictionary<object, string>(x);
    
        foreach (KeyValuePair<object;, string> i in y)  
        {  
            System.Console.WriteLine("The key is : "+i.Key+" and the value is : "+i.Value);  
        }
    }    
}


Output :



  The key is : 5 and the value is : Is a Number
  The key is : John and the value is : Is a Name
  The key is : C# and the value is : Is a Language

So, in the above code we have created a Dictionary and initialised to the variable x.


Dictionary<object, string> x = new Dictionary<object, string>()
{
	{ 5, "Is a Number" },
	{ "John", "Is a Name" },
	{ "C#", "Is a Language"}
};

Then we have created another Dictionary y and passed the above Dictionary x as Parameter.


Dictionary<object, string> y = new Dictionary<object, string>(x);
C_Sharp


And if we see the below output,


The key is : 5 and the value is : Is a Number
The key is : John and the value is : Is a Name
The key is : C# and the value is : Is a Language

The new variable y is an exact copy of x.


Note : Do not use the '=' operator to copy a Dictionary to the other(i.e. If there are two Dictionaries 'x' and 'y'. Do not use y = x). Because in that case any changes made to the Dictionary 'x' will be reflected in the copied Dictionary 'y'.