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




C# - UPDATE DICTIONARY


How to update the entries of a Dictionary?


Let us say, we have a Dictionary that contains,

5, Is a Number
John, Is a Name
C#, Is a Language

As Key and Value pair.


Now, let us say, we want to update the value of the Key, 5 with Is an one digit number.

5, Is an one digit number

Where 5 is the Key and Is an one digit number is the new Value.


Let us see in the below example.


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"}
        };
        
        x[5] = "Is an one digit number";
    
        foreach (KeyValuePair<object;, string> i in x)  
        {  
            System.Console.WriteLine("The key is : "+i.Key+" and the value is : "+i.Value);  
        }
    }    
}


Output :



  The key is : 5 and the value is : Is an one digit 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 using braces {} and Key and Value pairs.


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

And initialised to the variable x.

C_Sharp

Now, we are supposed to update the value of the Key, 5 with Is an one digit number.


So, we have used the below way to update it.


x[5] = "Is an one digit number";
C_Sharp


And the entry for the Key 5 is updated in the Dictionary.

C_Sharp

And we get the below output,

Output :



  The key is : 5 and the value is : Is an one digit number
  The key is : John and the value is : Is a Name
  The key is : C# and the value is : Is a Language