To iterate over the entries (key-value pairs) in a dictionary in C#, you can use a `foreach` loop to loop through the `KeyValuePair
We can iterate over the entries in a dictionary in C# using a `foreach` loop. This example demonstrates how to loop through the entries of a dictionary and print each key-value pair.
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>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
// Iterate over the entries in the dictionary
Console.WriteLine("Entries in the dictionary:");
foreach (KeyValuePair<int, string> kvp in myDictionary)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Entries in the dictionary: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
We can iterate over the entries in a dictionary in C# using a `foreach` loop and perform operations on the values. This example demonstrates how to loop through the entries of a dictionary, modify the values, and print each key-value pair.
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>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
// Iterate over the entries in the dictionary and modify values
Console.WriteLine("Modified entries in the dictionary:");
foreach (KeyValuePair<int, string> kvp in myDictionary)
{
string modifiedValue = kvp.Value.ToUpper();
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, modifiedValue);
}
}
}
Modified entries in the dictionary: Key: 1, Value: ONE Key: 2, Value: TWO Key: 3, Value: THREE
In this tutorial, we learned How to Iterate over Entries (Key-Value Pairs) in a Dictionary in C# language with well detailed examples.