Dictionary add key value pair
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 | class Program { static void Main(string[] args) { Dictionary<int, string> plants = new Dictionary<int, string>(); plants.Add(1, "Mahogany Birch"); plants.Add(2, "Silver Birch"); plants.Add(3, "Spice Birch"); Console.WriteLine("dictionary keys values....."); foreach (KeyValuePair<int, string> p in plants) { Console.WriteLine(p.Key + " | " + p.Value ); } //this line create a new keyvaluepair; KeyValuePair<int, string> pair = new KeyValuePair<int, string>(4, "Bay Laurel"); //this line new keyvaluepair to dictionary. plants.Add(pair.Key, pair.Value); Console.WriteLine("\nafter adding new key value pair...."); foreach (KeyValuePair<int, string> p in plants) { Console.WriteLine(p.Key + " | " + p.Value ); } Console.ReadLine(); } } |
Output:

How to add a key value pair to a Dictionary in C#