Adding to a Dictionary in C#
This post will discuss how to add to a Dictionary<TKey,TValue> in C#.
You can add key-value pairs to an existing dictionary using the Dictionary<TKey,TValue>.Add() method. It adds the specified key and value to the dictionary. The following example creates an empty dictionary and invokes the Add() method to add entries.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("A", 1); dict.Add("B", 2); dict.Add("C", 3); Console.WriteLine(String.Join(", ", dict)); } } |
Output:
[A, 1], [B, 2], [C, 3]
Note that the Add() method throws an ArgumentException when attempting to add a duplicate key, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("A", 1); dict.Add("B", 2); dict.Add("C", 3); Console.WriteLine(String.Join(", ", dict)); } } |
Output:
Unhandled exception. System.ArgumentException: An item with the same key has already been added. Key: A
The following version, using the indexer, does not throw an ArgumentException when inserting a duplicate key. It adds a new key-value pair if the key doesn’t already exist in the dictionary. Otherwise, it replaces the value of the specified key if an item with the same key already exists in the dictionary.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>(); dict["A"] = 1; dict["B"] = 2; dict["C"] = 3; Console.WriteLine(String.Join(", ", dict)); } } |
Output:
[A, 1], [B, 2], [C, 3]
That’s all about adding to a Dictionary<TKey,TValue> in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)