To add a key-value pair to a dictionary in C#, you can use the `Add` method of the `Dictionary
We can add a key-value pair to a dictionary in C# using the `Add` method. This example demonstrates how to add key-value pairs to a dictionary and print its contents.
For example,
using System.Collections.Generic;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
// Add key-value pairs to the dictionary
myDictionary.Add(1, "One");
myDictionary.Add(2, "Two");
myDictionary.Add(3, "Three");
// Print the dictionary contents
Console.WriteLine("Dictionary contents:");
foreach (KeyValuePair<int, string> kvp in myDictionary)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Dictionary contents: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
We can add or update a key-value pair in a dictionary in C# using the indexer. This example demonstrates how to add or update key-value pairs in a dictionary and print its contents.
For example,
using System.Collections.Generic;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
// Add or update key-value pairs in the dictionary using the indexer
myDictionary[1] = "One";
myDictionary[2] = "Two";
myDictionary[3] = "Three";
// Print the dictionary contents
Console.WriteLine("Dictionary contents:");
foreach (KeyValuePair<int, string> kvp in myDictionary)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Dictionary contents: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
In this tutorial, we learned How to Add a Key-Value Pair to a Dictionary in C# language with well detailed examples.