Dictionary update key
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | class Program { static void Main(string[] args) { //initialize a dictionary with keys and values. Dictionary<int, string> birds = new Dictionary<int, string>() { {1,"Australian Pelican"}, {2,"Brown Pelican"}, {3,"Pygmy Cormorant"} }; Console.WriteLine( "dictionary keys and values.........."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } //create a temporary dictionary Dictionary<int, string> temp = new Dictionary<int, string>(); foreach (KeyValuePair<int, string> pair in birds) { //set ney key is old key plus 10 int key = pair.Key + 10; temp.Add(key, pair.Value); } //assign temporary dictionary elements to old dictionary. birds = temp; Console.WriteLine("\n\ndictionary elements after updating keys.........."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 | dictionary keys and values.......... 1 ........ Australian Pelican 2 ........ Brown Pelican 3 ........ Pygmy Cormorant dictionary elements after updating keys.......... 11 ........ Australian Pelican 12 ........ Brown Pelican 13 ........ Pygmy Cormorant |