We can achieve this by creating a new dictionary and add the values to it.
// you can run this code here: https://www.programiz.com/csharp-programming/online-compiler/
// Online C# Editor for free
// Write, Edit and Run your C# code using C# Online Compiler
using System;
using System.Collections.Generic;
public class HelloWorld
{
public static void Main(string[] args)
{
var cities = new Dictionary<string, string>(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
//creating a new dictionary
var newVersion = new Dictionary<string, string>();
//print all the values exist in the cities
Console.WriteLine("..............Initial values in cities \n");
foreach (var kvp in cities) {
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
cities.Remove("UK"); // removes UK
//print all the values in the cities after removing "UK" and also add each value to the new dictionary
Console.WriteLine("\n ..............Values in cities after removal");
foreach (var kvp in cities) {
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
newVersion[kvp.Key] = kvp.Value;
}
//add new key value pairs to cities and new dictionary
cities["test"] = "test1";
cities["test2"] = "test2";
newVersion["test"] = "test1";
newVersion["test2"] = "test2";
//print values in the old dictionary
Console.WriteLine("\n..............Values in cities after adding new test values");
foreach (var kvp in cities) {
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
//print values in the new dictionary. New dictionary will add the values at the end
Console.WriteLine("\n..............New version");
foreach (var kvp in newVersion) {
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
}
}
**Sample output:**
..............**Initial values in cities**
Key = UK, Value = London, Manchester, Birmingham
Key = USA, Value = Chicago, New York, Washington
Key = India, Value = Mumbai, New Delhi, Pune
..............**Values in cities after removal**
Key = USA, Value = Chicago, New York, Washington
Key = India, Value = Mumbai, New Delhi, Pune
..............**Values in cities after adding new test values**
Key = test, Value = test1
Key = USA, Value = Chicago, New York, Washington
Key = India, Value = Mumbai, New Delhi, Pune
Key = test2, Value = test2
..............**New version**
Key = USA, Value = Chicago, New York, Washington
Key = India, Value = Mumbai, New Delhi, Pune
Key = test, Value = test1
Key = test2, Value = test2