Example of a C# code snippet that loops through a dictionary
In this code, a Dictionary
is created with strings as both keys and values. The foreach
loop iterates through each KeyValuePair
in the Dictionary
, and the key and value of each item are printed to the console.
csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create a new Dictionary
Dictionary<string, string> dictionary = new Dictionary<string, string>();
// Add some items
dictionary.Add(“Apple”, “Green”);
dictionary.Add(“Banana”, “Yellow”);
dictionary.Add(“Cherry”, “Red”);
// Loop through the Dictionary
foreach(KeyValuePair<string, string> item in dictionary)
{
Console.WriteLine(“Key: {0}, Value: {1}”, item.Key, item.Value);
}
}
}